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
For: | Use: | ||
& | & | ||
< | < | ||
> | > | ||
[ | [ | ||
] | ] |