Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
improve permutations
using @permutations avoids computing permutations($n - 1) several times

Signed-off-by: Moritz Lenz <moritz@faui2k3.org>
  • Loading branch information
grondilu authored and moritz committed Nov 15, 2015
1 parent 8ddc787 commit 57b83f4
Showing 1 changed file with 11 additions and 8 deletions.
19 changes: 11 additions & 8 deletions src/core/native_array.pm
Expand Up @@ -519,13 +519,16 @@ class array does Iterable is repr('VMArray') {
sub permutations(int $n) {
my int $i;
$n == 1 ?? ( (0,), ) !!
gather while $i < $n {
my Int @i;
my int $j;
@i.push($j++) while $j < $i;
$j = $i + 1;
@i.push($j++) while $j < $n;
take (nqp::clone($i), |@i[@$_]) for permutations($n - 1);
$i = $i + 1;
gather {
my @permutations = permutations($n - 1);
while $i < $n {
my Int @i;
my int $j;
@i.push($j++) while $j < $i;
$j = $i + 1;
@i.push($j++) while $j < $n;
take (nqp::clone($i), |@i[@$_]) for @permutations;
$i = $i + 1;
}
}
}

1 comment on commit 57b83f4

@grondilu
Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I've realized this loses laziness. For instance:

permutations(100)[0]

hangs. It shouldn't.

I suggest reverting this commit.

Please sign in to comment.