in reply to all binary combinations

sub bits { glob join "", map "{0,1}", 1..$_[0] } say for bits(10); __END__ 0000000000 0000000001 0000000010 0000000011 0000000100 0000000101 ... 1111111011 1111111100 1111111101 1111111110 1111111111

Update: On second thoughts, that's too long:

sub bits { glob "{0,1}" x $_[0] }
Yes, perlrocks, perl rocks!

Unless I state otherwise, all my code runs with strict and warnings

Replies are listed 'Best First'.
Re^2: all binary combinations
by ikegami (Patriarch) on Sep 04, 2009 at 17:09 UTC

    Yes, perlrocks, perl rocks!

    But glob is a re-implementation of csh's glob! ;)

      But that is one of Perl's strengths. It took the best of everything* that was out there, and stole it :-)

      *Apart from it's object system, obviously :-(

        Thanks FunkyMonk. But since glob is returning the whole list, and my list can be huge, i'm running out of memory. I would much rather have a way that generate one combination at a time where i'd choose whether to save it or not before getting the other combination. Looping would be great as opposed to returning the whole list at once.

        Any ideas?

        Thanks a lot

Re^2: all binary combinations
by perlrocks (Acolyte) on Sep 04, 2009 at 16:12 UTC
    mmmm thanks. But i don't really get it. Is there a way to save the solutions in a hash where each combination is a key? (i'm sure there is but i just don't know how :)
      To understand it, read the man page for glob. Then understand the following:

      print "$_\n" for glob "{0,1}"; # 0 1 print "$_\n" for glob "{0,1}{0,1}"; # 00 01 10 11 print "$_\n" for glob "{0,1}{0,1}{0,1}"; # 000 001 010 011 100 101 110 + 111

      Then read up on the repetition operator in perlop, and understand:

      print "AB" x 1; # AB print "AB" x 2; # ABAB print "AB" x 3; # ABABAB

      To use it to create keys in a hash, use something like

      use Data::Dumper; my %hash = map { $_ => 1 } glob "{0,1}" x 3; print Dumper \%hash; __END__ $VAR1 = { '011' => 1, '010' => 1, '111' => 1, '000' => 1, '101' => 1, '001' => 1, '100' => 1, '110' => 1 };


      Unless I state otherwise, all my code runs with strict and warnings
      Yes. Iterate over the results and use each result as a key.
        I figured that but the thing is that i don't know how and where the results are stored. I read about glob but that confused me more!!