... 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        


In reply to Re^2: One Zero variants_without_repetition (Al gor loops) by tye
in thread One Zero variants_without_repetition by thenetfreaker

Title:
Use:  <p> text here (a paragraph) </p>
and:  <code> code here </code>
to format your post, it's "PerlMonks-approved HTML":



  • 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:
    & &amp;
    < &lt;
    > &gt;
    [ &#91;
    ] &#93;
  • Link using PerlMonks shortcuts! What shortcuts can I use for linking?
  • See Writeup Formatting Tips and other pages linked from there for more info.