Here's another iterator solution that avoids the recursion altogether. There are three differences:
- It will return undef instead of an empty array ref if the number of items is less than the amount to choose (ie 3 choose 5).
- The amount to choose is passed before the list of items instead of afterwards because I thought it was weird, although your way does make sense if one thinks of it like "Here are 50 things, choose 5".
- The output order is a bit different.
All three of these can certainly be fixed, but I wanted to keep the code clear.
sub choose_n_iter {
my @todo = [ shift, [ @_ ], [] ];
return sub {
while ( @todo ) {
my ( $n, $pool, $tally ) = @{ shift @todo };
return $tally if $n == 0;
next if @$pool == 0;
my ( $first, @rest ) = @$pool;
push @todo, [ $n - 1, \@rest, [ @$tally, $first ]],
[ $n , \@rest, $tally ];
}
return;
};
}
And here is a more effecient version:
sub choose_n_iter {
my @todo = [ shift, [ @_ ], [] ];
return sub {
while ( @todo ) {
my ( $n, $pool, $tally ) = @{ shift @todo };
return $tally if $n == 0;
return [ @$tally, @$pool ] if $n == @$pool;
next if @$pool == 0;
my ( $first, @rest ) = @$pool;
push @todo, [ $n - 1, \@rest, [ @$tally, $first ]];
push @todo, [ $n , \@rest, $tally ] if @res
+t;
}
return;
};
}
Thanks goes out to
HOP for the recursion-to-iterator help.
-
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.