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
Posts are HTML formatted. Put <p> </p> tags around your paragraphs. Put <code> </code> tags around your code and data!
Titles consisting of a single word are discouraged, and in most cases are disallowed outright.
Read Where should I post X? if you're not absolutely sure you're posting in the right place.
Please read these before you post! —
Posts may use any of the Perl Monks Approved HTML tags:
- a, abbr, b, big, blockquote, br, caption, center, col, colgroup, dd, del, details, div, dl, dt, em, font, h1, h2, h3, h4, h5, h6, hr, i, ins, li, ol, p, pre, readmore, small, span, spoiler, strike, strong, sub, summary, sup, table, tbody, td, tfoot, th, thead, tr, tt, u, ul, wbr
You may need to use entities for some characters, as follows. (Exception: Within code tags, you can put the characters literally.)
| |
For: |
|
Use: |
| & | | & |
| < | | < |
| > | | > |
| [ | | [ |
| ] | | ] |
Link using PerlMonks shortcuts! What shortcuts can I use for linking?
See Writeup Formatting Tips and other pages linked from there for more info.