user
Task

**Generate** a sequence of permutations of n elements drawn from choice of k values.

This sequence will have   

n

k
{\displaystyle {\displaystyle n^{k}}}
   elements, unless the program decides to terminate early.

Do not store all the intermediate values of the sequence, rather generate them as required, and pass the intermediate result to a deciding routine for combinations selection and/or early generator termination.

For example: When "cracking" a *"combination"* lock a sequence is required, but the sequence is terminated once a successful *"combination"* is found. This case is a good example of where it is not required to store all the intermediate **permutations**.

**See Also:**

:   :   :   :   The number of samples of size k from n objects.
                  
                  
                With   combinations and permutations   generation tasks.

                |  | Order Unimportant | Order Important |
                | --- | --- | --- |
                | Without replacement | (  n k  )  =  n  C  k =    n ( n − 1 ) … ( n − k + 1 )  k ( k − 1 ) … 1 {\displaystyle {\displaystyle {\binom {n}{k}}=^{n}\operatorname {C} \_{k}={\frac {n(n-1)\ldots (n-k+1)}{k(k-1)\dots 1}}}} | n  P  k = n ⋅ ( n − 1 ) ⋅ ( n − 2 ) ⋯ ( n − k + 1 ) {\displaystyle {\displaystyle ^{n}\operatorname {P} \_{k}=n\cdot (n-1)\cdot (n-2)\cdots (n-k+1)}} |
                | Task: Combinations | Task: Permutations |
                | With replacement | (   n + k − 1 k  )  =  n + k − 1  C  k =    ( n + k − 1 ) !  ( n − 1 ) ! k ! {\displaystyle {\displaystyle {\binom {n+k-1}{k}}=^{n+k-1}\operatorname {C} \_{k}={(n+k-1)! \over (n-1)!k!}}} | n  k {\displaystyle {\displaystyle n^{k}}} |
                | Task: Combinations with repetitions | Task: Permutations with repetitions |
assistant
(formerly Perl 6)

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

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

**Works with**: rakudo version 2016.07

```
my @k = <a b c>;

.say for @k X @k;

```

For arbitrary 

n
{\displaystyle {\displaystyle n}}
:

**Works with**: rakudo version 2016.07

```
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 {\displaystyle k^{n}}}
 possibilities in base 

k
{\displaystyle {\displaystyle k}}
:

**Works with**: rakudo version 2016.07

```
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
```