Permutations: Difference between revisions
Content added Content deleted
Line 2,229: | Line 2,229: | ||
.say for [<a b c>], &next_perm ...^ !*;</lang> |
.say for [<a b c>], &next_perm ...^ !*;</lang> |
||
{{out}} |
|||
<pre>a b c |
|||
a c b |
|||
b a c |
|||
b c a |
|||
c a b |
|||
c b a |
|||
</pre> |
|||
Here is a non-recursive implementation, which works with any type. |
|||
<lang perl6> |
|||
sub permute(@items) { |
|||
my @seq := 1..+@items; |
|||
gather for (^[*] @seq) -> $n is copy { |
|||
my @order; |
|||
for @seq { |
|||
unshift @order, $n mod $_; |
|||
$n div= $_; |
|||
} |
|||
my @i-copy = @items; |
|||
take [ map { @i-copy.splice($_, 1) }, @order ]; |
|||
} |
|||
} |
|||
.say for permute( 'a'..'c' ) |
|||
</lang> |
|||
{{out}} |
{{out}} |
||
<pre>a b c |
<pre>a b c |