in reply to Re: One Zero variants_without_repetition
in thread One Zero variants_without_repetition
... 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, $/; }
- tye
|
|---|