Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Nativy and GLRify List.combinations
It's now about 25x faster
  • Loading branch information
lizmat committed Oct 22, 2015
1 parent e303970 commit 084e462
Showing 1 changed file with 34 additions and 20 deletions.
54 changes: 34 additions & 20 deletions src/core/List.pm
Expand Up @@ -6,28 +6,42 @@ my class X::Cannot::Empty { ... }
my class X::Immutable { ... }
my role Supply { ... }

my sub combinations($n, $k) {
my @result;
my @stack;

return ((),) unless $k;

@stack.push(0);
gather while @stack {
my $index = @stack - 1;
my $value = @stack.pop;

while $value < $n {
@result[$index++] = $value++;
@stack.push($value);
if $index == $k {
my @copy = @result.clone;
take infix:<,>(|@copy);
# take @result.map(-> $x { $x }).list;
$value = $n; # fake a last
my sub combinations(\n, \k) {
return ((),) if k < 1;

Seq.new(class :: does Iterator {
has int $!n;
has int $!k;
has Mu $!stack;
has Mu $!combination;
method BUILD(\n,\k) {
$!n = n;
$!k = k;
$!stack := nqp::list(0);
$!combination := nqp::list();
self
}
method new(\n,\k) { nqp::create(self).BUILD(n,k) }

method pull-one() {
my int $n = $!n;
my int $k = $!k;

while nqp::elems($!stack) {
my int $index = nqp::elems($!stack) - 1;
my int $value = nqp::pop($!stack);

while $value < $n && $index < $k {
nqp::bindpos($!combination,$index,+$value);
$index = $index + 1;
$value = $value + 1;
nqp::push($!stack,+$value);
}
return nqp::clone($!combination) if $index == $k;
}
IterationEnd
}
}
}.new(n,k))
}

# XXX This next function is only checked in to help
Expand Down

0 comments on commit 084e462

Please sign in to comment.