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># Lexicographic order
<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;
$j-- while $j >= 1 and [gt] @a[ $j, $j+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 [gt] $aj, @a[$k];
$k-- while $aj after @a[$k];

@a[ $j, $k ] .= reverse;
@a[ $j, $k ] .= reverse;


my $r = @a.end;
# This puts the tail end of permutation after jth position in
# increasing order.
my $s = $j + 1;
my Int $r = @a.end;
@a[ $r--, $s++ ] .= reverse while $r > $s;
my Int $s = $j + 1;
return @a;
while $r > $s {
@a[ $r, $s ] .= reverse;
$r--;
$s++;
}
}
}


my @array = < a b c >.sort;
.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>abc
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>