We don't bite newbies here... much PerlMonks

Re: Generate all unique combinations of 1 and 0 using specified length of "0"-string and count of 1's

by choroba (Cardinal)
 on Sep 18, 2020 at 07:09 UTC Need Help??

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]
• Comment on Re: Generate all unique combinations of 1 and 0 using specified length of "0"-string and count of 1's

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)

Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11121893]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this?Last hourOther CB clients
Other Users?
Others examining the Monastery: (4)
As of 2024-04-25 10:10 GMT
Sections?
Information?
Find Nodes?
Leftovers?
Voting Booth?

No recent polls found