Skip to main content

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)

Comments

Popular posts from this blog

creating first go program

for creating go program open your editor and paste this code, and save it as filename.go for example helloworld.go

package main import "fmt" func main() { fmt.Println("Hello, 世界") }
I will explain these codes in details for now , we will look how to run these code.

to run type go run helloworld.go  in terminal , we get


you can try golang online as well , golang