note
kelan
<p>
Here's another iterator solution that avoids the recursion altogether. There are three differences:
<ul>
<li>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).
</li>
<li>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".
</li>
<li>The output order is a bit different.
</li>
</ul>
All three of these can certainly be fixed, but I wanted to keep the code clear.
<code>
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;
};
}
</code>
And here is a more effecient version:
<code>
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 @rest;
}
return;
};
}
</code>
Thanks goes out to [http://hop.perl.plover.com|HOP] for the recursion-to-iterator help.
</p>
458418
458418