Pages

8/28/2014

Generate binary string of n bits


This N bit algorithm is based on generating the subsets of given size of input,The running time of this particular algorithm can be calculated by 2^n.If n = 4 There should be 2^4 subset which is the number of cycle taken by this particular algorithm.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
class NbitString
    def initialize(n)
        @a = Array.new(n)
        @n = n
    end

    def genString(n)
        if n < 1
            @a.each_slice(@n) { |a,b,c| puts [a,b,c]*'  '}
        else
            @a[n-1] = 0
            genString(n-1)
            @a[n-1] = 1
            genString(n-1)
        end
    end
end

nbit = NbitString.new(3)
nbit.genString(3)

No comments:

Post a Comment

widget

installing perl dancer in ubuntu

For installing perl dancer you need curl utility for installing curl ,   sudo apt-get install curl Now we can install Perl-Dancer by thi...