Description: | Semantic nitpicking:
Here are some ways to iterate over @S choose $K, all the $K-sized subsets of @S.
Finally, the code below which uses a similar principle as (tye)Re: Finding all Combinations, keeping track of a list of indices. The subsets are returned in the same order as a nested for-loop. Update: see Re^8: Perl6 Contest: Test your Skills for a verbose explanation of what this code does. |
sub combinations { my ($num, $arr) = @_; return sub { return } if $num == 0 or $num > @$arr; my @pick; return sub { return @$arr[ @pick = ( 0 .. $num - 1 ) ] unless @pick; my $i = $#pick; $i-- until $i < 0 or $pick[$i]++ < @$arr - $num + $i; return if $i < 0; @pick[$i .. $#pick] = $pick[$i] .. $#$arr; return @$arr[@pick]; }; }You use it like this:
my $iter = combinations( 3 => ['a' .. 'f'] ); while ( my @c = $iter->() ) { print "@c\n"; }
|
---|
Replies are listed 'Best First'. | |
---|---|
Re: Iterating over combinations
by Limbic~Region (Chancellor) on Sep 22, 2004 at 22:13 UTC | |
Re: Iterating over combinations
by Anonymous Monk on Feb 24, 2011 at 17:25 UTC |