Generate binary string of n bits in Ruby? -
this program generating binary strings of n bit.i getting wrong result in there duplication in answer.i couldn't figure out what's problem? here code:
class genstring def initialize(n) @a = array.new(n) end def binstring(n) if n < 0 @a.each_slice(3) { |a,b,c| puts [a,b,c]*' '} else @a[n-1] = 0 binstring(n-1) @a[n-1] = 1 binstring(n-1) end end end gen = genstring.new(3) gen.binstring(3)
the output is:
i highlighted repeated portions.
simply put: because you're telling print twice.
change condition inside #binstring
if n < 1
, , work fine.
see ideone: http://ideone.com/jjmtbh
i've noticed prints series backwards. can swap [a,b,c]
[c,b,a]
compensate this. i've changed ideone reflect this.
Comments
Post a Comment