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")
-
Are you posting in the right place? Check out Where do I post X? to know for sure.
-
Posts may use any of the Perl Monks Approved HTML tags. Currently these include the following:
<code> <a> <b> <big>
<blockquote> <br /> <dd>
<dl> <dt> <em> <font>
<h1> <h2> <h3> <h4>
<h5> <h6> <hr /> <i>
<li> <nbsp> <ol> <p>
<small> <strike> <strong>
<sub> <sup> <table>
<td> <th> <tr> <tt>
<u> <ul>
-
Snippets of code should be wrapped in
<code> tags not
<pre> tags. In fact, <pre>
tags should generally be avoided. If they must
be used, extreme care should be
taken to ensure that their contents do not
have long lines (<70 chars), in order to prevent
horizontal scrolling (and possible janitor
intervention).
-
Want more info? How to link
or How to display code and escape characters
are good places to start.
|