Skip to content

Instantly share code, notes, and snippets.

@ahalbert
Last active August 19, 2016 01:17
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ahalbert/1b495ad9facc504db0f7aa9fedc3ebe0 to your computer and use it in GitHub Desktop.
Save ahalbert/1b495ad9facc504db0f7aa9fedc3ebe0 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)[^1];
say combinations_with_replacement(('a','b','c'), 2)[^2];
say combinations_with_replacement(('a','b','c'), 2)[^3];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment