Skip to content

Instantly share code, notes, and snippets.

@grondilu
Last active December 9, 2015 19:54
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/61a28aca4bcb7ea423e4 to your computer and use it in GitHub Desktop.
Save grondilu/61a28aca4bcb7ea423e4 to your computer and use it in GitHub Desktop.
an other attempt at improving permutations, using the third method in http://rosettacode.org/wiki/Permutations#Perl_6
sub permutations(int $n) {
Seq.new:
class :: does Iterator {
has int $!n;
submethod BUILD { $!n = $n; self }
method pull-one {
return (^$!n).List unless (state $i = 0)++;
return IterationEnd if $i >= self.count-only;
return map { |(state @ = ^$!n).splice($_, 1) }, $i.polymod($!n ... 2);
}
method count-only { state $ = [*] 1 .. $!n }
}.new(:$n);
}
.say for permutations(3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment