Skip to content

Instantly share code, notes, and snippets.

@timo
Forked from ahalbert/cwr.p6
Last active August 18, 2016 23:18
Show Gist options
  • Save timo/e02e14a338e9358df1ba3b84d4f184b9 to your computer and use it in GitHub Desktop.
Save timo/e02e14a338e9358df1ba3b84d4f184b9 to your computer and use it in GitHub Desktop.
use v6;
use Test;
sub combinations_with_replacement(@iterable, $r) {
gather {
cwr(@iterable, [], $r);
}
}
sub cwr(@iterable, @state, $r) {
my $place = @state.elems;
@state.push(Nil);
for @iterable {
@state[$place] = $_[];
if $r > 1 {
cwr(@iterable, @state, $r-1);
@state.pop;
} else {
take @state[];
}
}
}
say combinations_with_replacement(('a','b','c'), 2);
#Output: ([a a] [a b] [a c] [b a] [b b] [b c] [c a] [c b] [c c])
is combinations_with_replacement(('a','b','c'), 2).List, (('a','a'), ('a','b'), ('a','c'), ('b','a'), ('b','b'), ('b','c'), ('c','a'), ('c','b'), ('c','c'));
# Failed test at t/itertools.t line 39
# expected: 'a a a b a c b a b b b c c a c b c c'
# got: 'c c c c c c c c c'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment