Last active
August 19, 2016 01:17
-
-
Save ahalbert/1b495ad9facc504db0f7aa9fedc3ebe0 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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