Last active
November 15, 2015 06:26
faster permutations for Perl 6
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
using @permutations, we avoid computing permutations($n - 1) several times