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 |

In Section
Seekers of Perl Wisdom

Comment onRe: Generate all unique combinations of 1 and 0 using specified length of "0"-string and count of 1'sSelectorDownloadCode