oooh, fun!

use strict; use warnings; my $zero = shift || 3; my $one = shift || 2; my @array = ( (0) x $zero, (1) x $one ); # print "@array\n"; print join ('', @array), "\n"; while (1) { my $cand = $#array; while ($cand) { if ($array[$cand-1] == 0 and $array[$cand] == 1) { ($array[$cand-1], $array[$cand]) = ($array[$cand], $array[ +$cand-1]); if ($cand < $#array) { @array[$cand+1..$#array] = sort @array[$cand+1..$#arra +y]; } last; } --$cand; } last unless $cand; # print "@array\n"; print join ('', @array), "\n"; }

Converting this to an iterator is left as an exercise to the reader (update:) remarkably trivial :)

sub iter { my $zero = shift || 3; my $one = shift || 2; my $init = 0; my @array = ( (0) x $zero, (1) x $one ); return sub { $init++ or return join('', @array); my $cand = $#array; while ($cand) { if ($array[$cand-1] == 0 and $array[$cand] == 1) { ($array[$cand-1], $array[$cand]) = ($array[$cand], $ar +ray[$cand-1]); if ($cand < $#array) { @array[$cand+1..$#array] = sort @array[$cand+1..$# +array]; } last; } --$cand; } return $cand ? join( '', @array) : undef; } } my $i = iter(@ARGV); while (my $str = $i->()) { print "$str\n"; }

update: tye was right (of course!), the sort may be advantageously replaced by a reverse. Furthermore, there is no point in reversing (or sorting) a one-element array...

$cand < $#array - 1 and @array[$cand+1..$#array] = reverse @array[$cand+1..$#array];

• another intruder with the mooring in the heart of the Perl


In reply to Re: One Zero variants_without_repetition by grinder
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.