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
|