Beefy Boxes and Bandwidth Generously Provided by pair Networks
Syntactic Confectionery Delight
 
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; }

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 studying the Monastery: (5)
As of 2016-06-29 02:46 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My preferred method of making French fries (chips) is in a ...











    Results (366 votes). Check out past polls.