Not obvious, but probably how I'd do it just because I wouldn't have to think about it. And I'm sure somebody else will soon point out a combinations module that has a version of 'pick' built in already.

#!/usr/bin/perl -l use strict; use Algorithm::Loops 'NestedLoops'; sub pick { my( $k, @chars ) = @_; my $idx = NestedLoops( [ ( sub { [ ( @_ ? 1+$_ : 0 ) .. @chars-$k+@_ ] } ) x $k ] ); return sub { @chars[ $idx->() ] }; } @ARGV = ( 3, 'a'..'e' ) if ! @ARGV; my $iter = pick( @ARGV ); while( my @subset = $iter->() ) { print "@subset"; }

Update: Oh, you didn't say whether or not you wanted "with replacement". It is slightly simpler with replacement:

( sub { [ ( @_ ? $_ : 0 ) .. $#chars ] } ) x $k

Update: I decided to combine the two and support shortcuts on the command-line. Code available via the "Select" (or "Download") link.

$ comb 10 10 | wc -l # with replacement 92378 $ comb -10 19 | wc -l # without replacement 92378

- tye        


In reply to Re: CPAN module to return successive combinations of n things taken k at a time (NestedLoops) by tye
in thread CPAN module to return successive combinations of n things taken k at a time by ibm1620

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.