I had an easier time thinking of this as manipulating the characteristic sequence of the subsets (i.e, a string of 0's and 1's, where the first bit is a 1 if the first factor is included in the subset, etc). If you look at the characteristic sequences given in your example, you can see that there are three rules being applied (you can print out $str to see what's going on under the covers). Anyway, this code does its manipulations on the characteristic sequence and converts it to the appropriate subset:
sub iter {
my @factors = @_;
my $str;
return sub {
if (not defined $str) {
$str = "1" . ("0" x $#factors);
return map { substr($str, $_, 1) ? $factors[$_] : () }
0 .. $#factors;
}
for ($str) {
s/0(0*)$/1$1/
or s/11$/01/
or s/^(.*)10(.*)$/"${1}01" . "0" x length $2/e
or return;
}
return map { substr($str, $_, 1) ? $factors[$_] : () }
0 .. $#factors;
};
}
my $i = iter( 2, 3, 5, 7 );
while (my @s = $i->()) {
print "@s\n";
}
__END__
2
2 3
2 3 5
2 3 5 7
2 3 7
2 5
2 5 7
2 7
3
3 5
3 5 7
3 7
5
5 7
7
I'd be interested to see this simplified a bit. I know you mentioned in the CB that
tye had an idea for a solution, and I wonder if he's able to implement it with manipulations to the subsets themselves instead of their characteristic sequences.
You also mentioned wanting to know when the "next phase" of iterations began (the horizontal lines in your example). You can figure this out by checking which substitution rule was actually applied.
Update: Here is the code with the "next phase" markers:
sub iter {
my @factors = @_;
my $str;
my $break = 0;
return sub {
if (not defined $str) {
$str = "1" . ("0" x $#factors);
return map { substr($str, $_, 1) ? $factors[$_] : () }
0 .. $#factors;
}
for ($str) {
s/0(0*)$/1$1/ and last;
return "BREAK" if $break = !$break;
s/11$/01/
or s/^(.*)10(.*)$/"${1}01" . "0" x length $2/e
or return;
}
return map { substr($str, $_, 1) ? $factors[$_] : () }
0 .. $#factors;
};
}
my $i = iter( 2, 3, 5, 7 );
while (my @s = $i->()) {
print "@s\n";
}
__END__
2
2 3
2 3 5
2 3 5 7
BREAK
2 3 7
BREAK
2 5
2 5 7
BREAK
2 7
BREAK
3
3 5
3 5 7
BREAK
3 7
BREAK
5
5 7
BREAK
7
BREAK
-
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.