Permutations: Difference between revisions

338 bytes removed ,  12 years ago
→‎{{header|Perl 6}}: borrow simplified code from dinesman
No edit summary
(→‎{{header|Perl 6}}: borrow simplified code from dinesman)
Line 1,046:
</pre>
=={{header|Perl 6}}==
<lang perl6>#sub Lexicographicnext_perm order( @a is copy ) {
sub next_perm ( @a ) {
# j is the largest index with a[j] < a[j+1].
my $j = @a.end - 1;
$jreturn Nil if -- while $j >=< 10 andwhile @a[gt$j] after @a[ $j, $j+1 ];
 
# a[k] is the smallest integer greater than a[j] to the right of a[j].
my $aj = @a[$j];
my $k = @a.end;
$k-- while [gt] $aj, after @a[$k];
 
@a[ $j, $k ] .= reverse;
 
my $r = $r--@a.end;
# This puts the tail end of permutation after jth position in
#my increasing$s order.= $j + 1;
my Int@a[ $r--, =$s++ ] @a.end= reverse while $r > $s;
myreturn Int $s = $j + 1@a;
while $r > $s {
@a[ $r, $s ] .= reverse;
$r--;
$s++;
}
}
 
my.say @array =for [< a b c >], &next_perm .sort..^ !*;</lang>
my $perm_count = [*] 1 .. +@array; # Factorial
for ^$perm_count {
@array.say;
next_perm(@array);
}
</lang>
 
Output:<pre>abca b c
a c b
acb
b a c
bac
b c a
bca
c a b
cab
c b a
cba
</pre>
 
Anonymous user