Beefy Boxes and Bandwidth Generously Provided by pair Networks
Perl-Sensitive Sunglasses
 
PerlMonks  

Re: Iterating over combinations

by Anonymous Monk
on Feb 24, 2011 at 17:25 UTC ( #890022=note: print w/ replies, xml ) Need Help??


in reply to Iterating over combinations

Another solution...

### Example Usage: my $Text = "The quick brown fox jumps over the lazy dog"; my @Words = split(/ /, $Text); printf("%s (%d words)\n", $Text, scalar @Words); print "-"x100 . "\n"; foreach my $I (1..3) { my @Results = Combinations($I, @Words); printf("Found %d combinations of %d words from '%s'\n", scalar @Results, $I, $Text); printf(" (%s)\n", join("|", @$_) ) foreach (@Results); print "-"x100 . "\n"; } ### Actual Useful Part: sub Combinations { my $PickSize = shift; my @Elements = @_; my @RValue; my $StopAt = scalar(@Elements) - ($PickSize-1) - 1; return ([]) if $PickSize == 0; return ([]) if $PickSize > scalar(@Elements); for(my $i=0; $i<=$StopAt; $i++) { my $Element = $Elements[$i]; my @Rest = @Elements; splice(@Rest, 0, $i+1); foreach ( Combinations($PickSize-1, @Rest) ) { my @NewElement = ($Element, @$_); push(@RValue, \@NewElement ); } } return @RValue; }


Comment on Re: Iterating over combinations
Download Code

Log In?
Username:
Password:

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

How do I use this? | Other CB clients
Other Users?
Others lurking in the Monastery: (14)
As of 2014-10-23 15:54 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    For retirement, I am banking on:










    Results (125 votes), past polls