Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
move combinations/permutations subs out of List
  • Loading branch information
TimToady committed Jan 24, 2014
1 parent 8ae2ded commit 80c1e76
Showing 1 changed file with 28 additions and 27 deletions.
55 changes: 28 additions & 27 deletions src/core/List.pm
@@ -1,6 +1,34 @@
# for our tantrums
my class X::TypeCheck { ... }

my sub combinations($n, $k) {
my @result;
my @stack;
@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 {
take [@result];
$value = $n; # fake a last
}
}
}
}

my sub permutations(Int $n) {
$n == 1 ?? ( [0,] ) !!
gather for ^$n -> $i {
my @i = grep none($i), ^$n;
take [$i, @i[@$_]] for permutations($n - 1);
}
}

my class List does Positional { # declared in BOOTSTRAP
# class List is Iterable is Cool
# has Mu $!items; # VM's array of our reified elements
Expand Down Expand Up @@ -534,26 +562,6 @@ my class List does Positional { # declared in BOOTSTRAP
nqp::bindpos($!items, nqp::unbox_i(pos), v)
}

my sub combinations($n, $k) {
my @result;
my @stack;
@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 {
take [@result];
$value = $n; # fake a last
}
}
}
}

proto method combinations($?) {*}
multi method combinations( Int $of ) {
[self[@$_]] for combinations self.elems, $of
Expand All @@ -565,13 +573,6 @@ my class List does Positional { # declared in BOOTSTRAP
}
}

my sub permutations(Int $n) {
$n == 1 ?? ( [0,] ) !!
gather for ^$n -> $i {
my @i = grep none($i), ^$n;
take [$i, @i[@$_]] for permutations($n - 1);
}
}
method permutations() {
gather take self[@$_] for permutations self.elems;
}
Expand Down

0 comments on commit 80c1e76

Please sign in to comment.