Skip to content

Instantly share code, notes, and snippets.

@grondilu
Last active November 15, 2015 06:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save grondilu/115db8332c875b440ba8 to your computer and use it in GitHub Desktop.
Save grondilu/115db8332c875b440ba8 to your computer and use it in GitHub Desktop.
faster permutations for Perl 6
sub permutations(int $n) {
my int $i;
$n == 1 ?? ( (0,), ) !!
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;
}
}
}
@grondilu
Copy link
Author

using @permutations, we avoid computing permutations($n - 1) several times

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment