RosettaCodeData/Task/Combinations/Perl-6/combinations-2.pl6

16 lines
375 B
Raku
Raw Permalink Normal View History

2013-10-27 22:24:23 +00:00
sub combinations(Int $n, Int $k) {
2015-02-20 00:35:01 -05:00
return ([],) unless $k;
return if $k > $n || $n <= 0;
my @c = ^$k;
gather loop {
take [@c];
next if @c[$k-1]++ < $n-1;
my $i = $k-2;
$i-- while $i >= 0 && @c[$i] >= $n-($k-$i);
last if $i < 0;
@c[$i]++;
while ++$i < $k { @c[$i] = @c[$i-1] + 1; }
2013-10-27 22:24:23 +00:00
}
}
2015-02-20 00:35:01 -05:00
.say for combinations(5,3);