I had my own idea of how to do it, and I came up with restartable iterators: #!/usr/bin/perl
use strict;
use warnings;
sub restartable_iter {
my ($start, $end) = @_;
sub {
$start = shift if @_;
return if $start > $end;
$start++;
}
}
sub choose_m_of_n_iter {
my ($m, $n) = @_;
my @iter;
for my $i (0..($m-1)) {
push @iter, restartable_iter($i, $n-$m+$i);
}
join_iter(@iter);
}
sub join_iter {
my $it = shift;
while ( my $tmp = shift ) {
$it = append_iter( $it, $tmp );
}
$it;
}
sub append_iter {
my ($it1, $it2) = @_;
my (@ret1, @ret2) = $it1->();
sub {
return @ret1, @ret2 if @ret2 = $it2->();
return unless @ret1 = $it1->();
return @ret1, $it2->($ret1[-1]+1);
}
}
my $iter = choose_m_of_n_iter(4, 10);
while (my @arr = $iter->()) {
print "@arr\n";
}
In the append iterator, when the second iterator is exhausted, it causes the first iterator to iterate, and then restarts the second iterator at the appropriate starting point.
Update:Unlike the other solutions, the solution above returns an array of indices instead of a set of elements from a list,
but that's easy to adjust: sub choose_n {
my $n = shift;
my @set = @_;
my $iter = choose_m_of_n_iter($n, scalar(@set));
sub {
@set[$iter->()];
}
}
Update: Simplified code. Which may or may not be a good thing :-)
-
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.
|