in reply to Finding all Combinations
Sure. No need to do any recursion here. Just count in binary. Here is a version that creates a closure (an anonymous subroutine that holds the needed data inside of itself -- sort of like a tiny "object") that returns the next combination each time it is called:
sub combinations { my @list= @_; my @pick= (0) x @list; return sub { my $i= 0; while( 1 < ++$pick[$i] ) { $pick[$i]= 0; return if $#pick < ++$i; } return @list[ grep $pick[$_], 0..$#pick ]; }; } my $next= combinations( 50..59 ); my @comb; while( @comb= $next->() ) { # do work with @comb here } # Note that the empty set is a valid combination but is # the last combination returned which also indicates "no # more combinations left. So the above loop doesn't bother # processing the empty list. If you want to process the # empty set, then use: my @comb; do { # do work with @comb here } while( @comb= $next->() );
Update: My code finds combinations but the original code finds permutations even though the author asked for combinations. (See (tye)Re: Permutations if you don't know the difference between the two.)
Of course, my favorite way of finding permutations is Permuting with duplicates and no memory.
- tye (but my friends call me "Tye")
|
---|
Replies are listed 'Best First'. | |
---|---|
Re^2: Finding all Combinations
by Limbic~Region (Chancellor) on Sep 27, 2004 at 14:06 UTC | |
by tye (Sage) on Oct 01, 2004 at 20:49 UTC | |
by roboticus (Chancellor) on Jun 23, 2006 at 14:21 UTC | |
by Limbic~Region (Chancellor) on Jun 23, 2006 at 17:35 UTC | |
by roboticus (Chancellor) on Jun 23, 2006 at 23:07 UTC | |
by Limbic~Region (Chancellor) on Jun 24, 2006 at 17:30 UTC | |
Re: (tye)Re: Finding all Combinations
by dragonchild (Archbishop) on Nov 29, 2001 at 19:01 UTC | |
Re: (tye)Re: Finding all Combinations
by redbeard (Beadle) on Sep 10, 2002 at 23:48 UTC | |
by tye (Sage) on Sep 11, 2002 at 17:38 UTC | |
by redbeard (Beadle) on Sep 11, 2002 at 22:36 UTC | |
by tye (Sage) on Sep 12, 2002 at 05:43 UTC |
In Section
Seekers of Perl Wisdom