Permutations: Difference between revisions
Content added Content deleted
No edit summary |
(→{{header|Perl 6}}: borrow simplified code from dinesman) |
||
Line 1,046: | Line 1,046: | ||
</pre> |
</pre> |
||
=={{header|Perl 6}}== |
=={{header|Perl 6}}== |
||
<lang perl6> |
<lang perl6>sub next_perm ( @a is copy ) { |
||
sub next_perm ( @a ) { |
|||
# j is the largest index with a[j] < a[j+1]. |
|||
my $j = @a.end - 1; |
my $j = @a.end - 1; |
||
return Nil if --$j < 0 while @a[$j] after @a[$j+1]; |
|||
# a[k] is the smallest integer greater than a[j] to the right of a[j]. |
|||
my $aj = @a[$j]; |
my $aj = @a[$j]; |
||
my $k = @a.end; |
my $k = @a.end; |
||
$k-- while |
$k-- while $aj after @a[$k]; |
||
@a[ $j, $k ] .= reverse; |
@a[ $j, $k ] .= reverse; |
||
⚫ | |||
# This puts the tail end of permutation after jth position in |
|||
my $s = $j + 1; |
|||
@a[ $r--, $s++ ] .= reverse while $r > $s; |
|||
return @a; |
|||
while $r > $s { |
|||
@a[ $r, $s ] .= reverse; |
|||
⚫ | |||
$s++; |
|||
} |
|||
} |
} |
||
.say for [<a b c>], &next_perm ...^ !*;</lang> |
|||
my $perm_count = [*] 1 .. +@array; # Factorial |
|||
for ^$perm_count { |
|||
@array.say; |
|||
next_perm(@array); |
|||
} |
|||
</lang> |
|||
Output:<pre> |
Output:<pre>a b c |
||
a c b |
|||
acb |
|||
b a c |
|||
bac |
|||
b c a |
|||
bca |
|||
c a b |
|||
cab |
|||
c b a |
|||
cba |
|||
</pre> |
</pre> |
||