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:

enter image description here

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

Popular posts from this blog

javascript - RequestAnimationFrame not working when exiting fullscreen switching space on Safari -

Python ctypes access violation with const pointer arguments -