Semantic nitpicking: (tye)Re: Finding all Combinations is a canonical way to iterate over a set's power set. It won't get you combinations in the above sense (a better name would be (tye)Re: Finding all Subsets). Permuting with duplicates and no memory is a canonical way to iterate over permutations.

Here are some ways to iterate over @S choose $K, all the $K-sized subsets of @S.

## Filtering tye's "combinations" (power set) iterator: my $iter = combinations(@S); while ( my @c = $iter->() ) { next unless @c == $K; ... }
## Using tye's Algorithm::Loops: NestedLoops( [ 0 .. $#S ], ( sub { [$_+1 .. $#S] } ) x ($K - 1), sub { my @c = @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"; }

In reply to Iterating over combinations by blokhead

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
  • Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
  • Read Where should I post X? if you're not absolutely sure you're posting in the right place.
  • Please read these before you post! —
  • Posts may use any of the Perl Monks Approved HTML tags:
    a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
  • You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
            For:     Use:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.