Beefy Boxes and Bandwidth Generously Provided by pair Networks
Come for the quick hacks, stay for the epiphanies.
 
PerlMonks  

Re: CPAN module to return successive combinations of n things taken k at a time (NestedLoops)

by tye (Sage)
on Feb 26, 2015 at 04:14 UTC ( [id://1117904]=note: print w/replies, xml ) Need Help??


in reply to CPAN module to return successive combinations of n things taken k at a time

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        

  • Comment on Re: CPAN module to return successive combinations of n things taken k at a time (NestedLoops)
  • Select or Download Code

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://1117904]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others drinking their drinks and smoking their pipes about the Monastery: (2)
As of 2024-04-19 19:02 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found