Beefy Boxes and Bandwidth Generously Provided by pair Networks
Your skill will accomplish
what the force of many cannot

comment on

( #3333=superdoc: print w/replies, xml ) Need Help??
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 :-)

In reply to Re: Recursively-generated Iterators by runrig
in thread Recursively-generated Iterators by Roy Johnson

Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post; it's "PerlMonks-approved HTML":

  • 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.
Log In?

What's my password?
Create A New User
Domain Nodelet?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others browsing the Monastery: (3)
As of 2022-12-03 08:42 GMT
Find Nodes?
    Voting Booth?

    No recent polls found