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

Re: One Zero variants_without_repetition

by BrowserUk (Patriarch)
on Aug 07, 2007 at 10:56 UTC ( [id://631009]=note: print w/replies, xml ) Need Help??


in reply to One Zero variants_without_repetition

Do you mean like this?

print unpack 'B8', chr for 0 .. 255;; 00000000 00000001 00000010 00000011 00000100 00000101 ... 11111011 11111100 11111101 11111110 11111111

Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
"Science is about questioning the status quo. Questioning authority".
In the absence of evidence, opinion is indistinguishable from prejudice.

Replies are listed 'Best First'.
Re^2: One Zero variants_without_repetition
by thenetfreaker (Friar) on Aug 07, 2007 at 11:03 UTC
    no, i need to print all the variations with a spesific number of ones and zeroes without repeats, for example all the variants with 6 zeroes and 14 ones.
    as i gave the example earlier with 2 ones and 3 zeroes.

      Okay, sorry! Try this iterator then. It will handle upto 32 0s + 1s.

      If you uncomment the second example it runs on a bit.

      Update: Had to tweak the termination condition. It works now but I'm not happy with it.

      Update2: D'oh! No need to count both 1s and 0s.

      #! perl -slw use strict; sub combs { my( $ones, $zeros ) = @_; my $n = $ones+$zeros; my $max = 2**$n; my $p = 0; return sub { my $x = ''; $x = unpack "b$n", pack 'V', $p++ until $x =~ tr[1][] == $ones or $p > $max and return; return $x; } } my $iter = combs( 2, 3 ); print while $_ = $iter->(); #my $iter = combs( 14, 6 ); #print while $_ = $iter->(); __END__ C:\test>junk7 11000 10100 01100 10010 01010 00110 10001 01001 00101 00011

      Examine what is said, not who speaks -- Silence betokens consent -- Love the truth but pardon error.
      "Science is about questioning the status quo. Questioning authority".
      In the absence of evidence, opinion is indistinguishable from prejudice.
        That's a very nice algorythm, but it's a bit slow, and 2 questions:
        1. how can i work with (much)more that 32 1's+0's ?
        2. why do i need $max to be 2**$n ? when combs(2,3) gives 10 reasults not 32 ???

        i need this sub{} to play with the strings that contain that number of 1's and 0's, not the numbers that contain them.

Log In?
Username:
Password:

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

How do I use this?Last hourOther CB clients
Other Users?
Others avoiding work at the Monastery: (5)
As of 2024-04-19 09:47 GMT
Sections?
Information?
Find Nodes?
Leftovers?
    Voting Booth?

    No recent polls found