blokhead,
I doubt this is how tye would have implemented it, but this is 1 implementation of his 3 simple rules:
#!/usr/bin/perl
use strict;
use warnings;
my $next = iter_powerset( 1,2,3,4,5 );
while ( my @combo = $next->() ) {
print "@combo\n";
}
sub iter_powerset {
my @factor = @_;
my $end = $#factor;
my @subset = (undef) x $end;
my ($pos, $mode) = (-1, 1);
my $return = sub { return @factor[ grep defined, @subset ] };
my %dispatch = (
1 => sub {
++$pos;
$subset[ $pos ] = $pos;
++$mode if $pos == $end;
$return->();
},
2 => sub {
$subset[ $pos - 1 ] = undef;
++$mode;
$return->();
},
3 => sub {
$subset[ $pos-- ] = undef;
while ( $pos >= 0 ) {
last if defined $subset[ $pos ];
--$pos;
}
$subset[ $pos++ ] = undef;
return () if ! $pos;
$subset[ $pos ] = $pos;
$mode = 1;
$return->();
},
);
return sub { $dispatch{ $mode }->() };
}
I am now going to play with making it closer to what I want for the other task.
Since tye's 3 simple rules were uttered in passing on the CB, I will summarize them here to help explain the code
- Mode 1: Fill to the right until you reach the end
- Mode 2: Remove second to last element
- Mode 3: Remove last element, increment new last element
-
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.
|