Recursion is the trick:
use strict; use warnings; print "$_\n" for GenUniStrings(3, 10); sub GenUniStrings { my ($numOnes, $strLen) = @_; my @strings; die "Number of ones can't be zero or negative" if $numOnes < 1; for my $prefixSize (0 .. $strLen - $numOnes) { my $prefix = '0' x $prefixSize; my $tailLen = $strLen - $prefixSize - 1; if ($numOnes == 1) { push @strings, $prefix . '1' . ('0' x $tailLen); } else { push @strings, map {$prefix . '1' . $_} GenUniStrings($numOnes - 1, $tailLen); } } return @strings; }
Prints:
1110000000 1101000000 1100100000 1100010000 ...till... 0000001110 0000001101 0000001011 0000000111
Update: minor code tidy
In reply to Re: Generate all unique combinations of 1 and 0 using specified length of "0"-string and count of 1's
by GrandFather
in thread Generate all unique combinations of 1 and 0 using specified length of "0"-string and count of 1's
by Lana
| For: | Use: | ||
| & | & | ||
| < | < | ||
| > | > | ||
| [ | [ | ||
| ] | ] |