Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Merge pull request #631 from grondilu/patch-8
improve permutations
  • Loading branch information
lizmat committed Dec 13, 2015
2 parents 091f0ce + 4cf0862 commit e52617c
Showing 1 changed file with 6 additions and 11 deletions.
17 changes: 6 additions & 11 deletions src/core/native_array.pm
Expand Up @@ -731,24 +731,19 @@ sub permutations(int $n where $n > 0) {
# Find the largest index k such that a[k] < a[k + 1].
# If no such index exists, the permutation is the last permutation.
my int $k = @!a.end - 1;
$k-- until $k < 0 or @!a[$k] < @!a[$k + 1];
return IterationEnd if $k < 0;
$k-- or return IterationEnd until @!a[$k] < @!a[$k + 1];

# Find the largest index l greater than k such that a[k] < a[l].
my int $l = @!a.end;
$l-- until @!a[$k] < @!a[$l];
# use L<https://en.wikipedia.org/wiki/XOR_swap_algorithm>
# @!a[$k, $l].=reverse
@!a[$k] +^= @!a[$l];
@!a[$k] +^= @!a[$l] = @!a[$k] +^ @!a[$l];

(@!a[$k] +^= @!a[$l]) +^= @!a[$l] +^= @!a[$k];

# @!a[$k+1 .. @!a.end].=reverse;
$l = $!n;
until ++$k >= --$l {
@!a[$k] +^= @!a[$l];
@!a[$k] +^= @!a[$l] = @!a[$k] +^ @!a[$l];
}
@!a.List;
}
(@!a[$k] +^= @!a[$l]) +^= @!a[$l] +^= @!a[$k] until ++$k >= --$l;
@!a.List; }
method count-only { [*] 1 .. $!n }
}.new(:$n)
);
Expand Down

0 comments on commit e52617c

Please sign in to comment.