From: Robert Dober Date: 2009-08-10T04:08:26+09:00 Subject: Re: Generate binary sequences of length n? On Sun, Aug 9, 2009 at 8:32 PM, David A. Black wrote: > Hi -- > > On Mon, 10 Aug 2009, Tom Best wrote: > >> I'm rather new to Ruby.  I feel this should be very simple, but I'm >> having trouble: >> >> I'd like to write a script to work through all possible binary sequences >> of length n. >> >> >> >> The script would work as follows: >> >> mylength = 4 >> resultz = binary_seq_generator(mylength) >> puts "#{resultz}" >> >> #resultz, not necessarily in this order: >> >> ["0000","0001","0010","0011","0100","0101","0110","0111","1000","1001","1010","1011","1100","1101","1110","1111"] > > Try this: > > def binary_seq_generator(n) >  (0...(1 << n)).map {|e| "%0#{n}d" % e.to_s(2) } > end > > Doesn't necessarily roll off the fingers as readily as some Ruby > idioms do :-) But I think all or most of what you need is there, and > there are some interesting bits to it. Well 1.9 has to offer some elegance here (1<