Beefy Boxes and Bandwidth Generously Provided by pair Networks
Just another Perl shrine
 
PerlMonks  

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

by Eily (Monsignor)
on Sep 18, 2020 at 09:43 UTC ( #11121908=note: print w/replies, xml ) Need Help??


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% --

Log In?
Username:
Password:

What's my password?
Create A New User
Domain Nodelet?
Node Status?
node history
Node Type: note [id://11121908]
help
Chatterbox?
and the web crawler heard nothing...

How do I use this? | Other CB clients
Other Users?
Others exploiting the Monastery: (1)
As of 2021-10-21 05:29 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?
    My first memorable Perl project was:







    Results (82 votes). Check out past polls.

    Notices?