Permutations with repetitions

We can use the X operator ("cartesian product") to cross the list with itself.

For n = 2 {\displaystyle n=2} :

my @k = <a b c>;

.say for @k X @k;

For arbitrary n {\displaystyle n} :

my @k = <a b c>;
my $n = 2;

.say for [X] @k xx $n;

Output:

a a
a b
a c
b a
b b
b c
c a
c b
c c

Here is an other approach, counting all k n {\displaystyle k^{n}} possibilities in base k {\displaystyle k} :

my @k = <a b c>;
my $n = 2;

say @k[.polymod: +@k xx $n-1] for ^@k**$n

Output:

a a
b a
c a
a b
b b
c b
a c
b c
c c

Last updated

Was this helpful?