Beefy Boxes and Bandwidth Generously Provided by pair Networks
go ahead... be a heretic

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?

What's my password?
Create A New User
Node Status?
node history
Node Type: note [id://890022]
and all is quiet...

How do I use this? | Other CB clients
Other Users?
Others musing on the Monastery: (6)
As of 2017-06-24 03:02 GMT
Find Nodes?
    Voting Booth?
    How many monitors do you use while coding?

    Results (556 votes). Check out past polls.