in reply to Re: Generate all unique combinations of 1 and 0 using specified length of "0"-string and count of 1's [Updated]
in thread Generate all unique combinations of 1 and 0 using specified length of "0"-string and count of 1's

With the power of Perlmonks::Combinatorics I combined Lanx's solution and mine:

sub Eily_LanX { my ($length, $ones) = @_; my $iter = combinations([0..$length-1], $ones); my (@r, $str); while (my $positions = $iter->next) { $str = '0' x $length; substr $str, $_, 1, '1' for @$positions; push @r, $str; } return \@r }
Rate salva tybalt89_re choroba tybalt89 Eily GrandFather + Eily_LanX salva 795/s -- -10% -57% -59% -62% -84% + -85% tybalt89_re 879/s 11% -- -52% -54% -59% -82% + -83% choroba 1842/s 132% 110% -- -4% -13% -63% + -64% tybalt89 1916/s 141% 118% 4% -- -10% -61% + -63% Eily 2120/s 167% 141% 15% 11% -- -57% + -59% GrandFather 4960/s 524% 464% 169% 159% 134% -- + -4% Eily_LanX 5154/s 548% 486% 180% 169% 143% 4% + --

  • Comment on Re^2: Generate all unique combinations of 1 and 0 using specified length of "0"-string and count of 1's
  • Select or Download Code

Replies are listed 'Best First'.
Re^3: Generate all unique combinations of 1 and 0 using specified length of "0"-string and count of 1's
by vr (Curate) on Sep 19, 2020 at 11:49 UTC

    I remember, some time ago, looking under the hood of Algorithm::Combinatorics, to find it somewhat inefficient. The ntheory equivalents, if they exist, are faster:

    use ntheory 'forcomb'; sub Eily_LanX_vr { my ( $length, $ones ) = @_; my ( $str, $s, @r ); $str = '0' x $length; forcomb { $s = $str; substr $s, $_, 1, '1' for @_; push @r, $s; } $length, $ones; return \@r } cmpthese(-3, { Eily_LanX_vr => sub { Eily_LanX_vr(25, 5) }, Eily_LanX => sub { Eily_LanX(25, 5) }, }); __END__ Rate Eily_LanX Eily_LanX_vr Eily_LanX 11.9/s -- -59% Eily_LanX_vr 29.0/s 143% --