http://qs1969.pair.com?node_id=11121893


in reply to Generate all unique combinations of 1 and 0 using specified length of "0"-string and count of 1's

The function to generate all binary numbers was shown in the solution to the Perl Weakly Challenge 049. Iterate its results and use tr to count the occurrences of ones:
#!/usr/bin/perl use warnings; use strict; use feature qw{ say }; sub increment { my $pos = rindex $_[0], 0; if ($pos > -1) { substr $_[0], $pos, 1, '1'; substr $_[0], $pos + 1, length($_[0]) - $pos - 1, '0' x (length($_[0]) - $pos - 1); } else { $_[0] = '1' . ('0' x length $_[0]); } } my $ones = 3; my $length = 10; my $n = '0' x $length; while ($length == length $n) { increment($n); next unless $ones == $n =~ tr/1//; say $n; }

map{substr$_->[0],$_->[1]||0,1}[\*||{},3],[[]],[ref qr-1,-,-1],[{}],[sub{}^*ARGV,3]

Replies are listed 'Best First'.
Re^2: Generate all unique combinations of 1 and 0 using specified length of "0"-string and count of 1's
by salva (Canon) on Sep 18, 2020 at 07:38 UTC
    Generating all the combination and then filtering out those that don't have the right number of ones can be pretty inefficient, specially when the number of zeros is big and the number of ones small.

    In any case, you can also use a regular expression for generating all the binary numbers of some given length :-)

    my $length = 5; my $str = "0" x $length; my $start = $str . "1"; do { print "$str\n"; } while ($str =~ s/^(1*0)/substr $start, -length $1/e)