... which is available as Algorithm::Loops::NextPermute().
And Algorithm::Loops offers another way to do this as well.
use strict;
use Algorithm::Loops qw( NestedLoops );
my $bits= 8;
my $ones= 5;
my $iter= NestedLoops(
[ [ 0 .. $bits-1 ],
( sub {
[ 1+$_[-1] .. $bits-1 ]
}
) x ($ones-1),
],
);
my @ones;
while( @ones= $iter->() ) {
my @bits= (0) x $bits;
@bits[@ones]= (1) x $ones;
print join '', @bits, $/;
}
Which is like
my $bits= 8;
for my $o0 ( 0 .. $bits-1 ) {
for my $o1 ( 1+$o0 .. $bits-1 ) {
for my $o2 ( 1+$o1 .. $bits-1 ) {
for my $o3 ( 1+$o2 .. $bits-1 ) {
for my $o4 ( 1+$o3 .. $bits-1 ) {
my @bits= (0) x $bits;
@bits[$o0,$o1,$o2,$o3,$o4]= (1)x5;
}
}
}
}
}
Except that the number of ones (and thus the number of nested loops) isn't hard-coded.
Update: You can also avoid some looping at the tail end by setting tight top limits:
use strict;
use Algorithm::Loops qw( NestedLoops );
my $bits= 8;
my $ones= 5;
my $iter= NestedLoops(
[ [ 0 .. $bits - $ones ],
map(
{ # Need lexical for closure
my $top= $bits - $ones + $_;
sub {
[ 1+$_[-1] .. $top ]
}
}
1 .. $ones-1,
),
],
);
my @ones;
while( @ones= $iter->() ) {
my @bits= (0) x $bits;
@bits[@ones]= (1) x $ones;
print join '', @bits, $/;
}
-
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.