Generate n-bits sequence code in Javascript

on

Recently, I came across code challenge to generate n-bits sequence code in Javascript.
The challenge was need to create a function to print the n-bit sequence codes by given number.
I’m just sharing the coding experience here, so someone will get benifited in feature visitor.

Example : 2-bit code sequences

Input : 2

Output :

00
01
11
10

Example : 3-bit code sequences

Input : 3
Output :

000
001
011
010
110
111
101
100

Lets look at the code straight a way!

 

// Adding paddng to the number in js
function pad(size,n) {
  var s = String(n);
  while (s.length < (size || 2)) {s = "0" + s;}
  return s;
}

// Function to convert decimal to binnary in js
function dec2bin(dec){
    return (dec >>> 0).toString(2);
}
 
// Function to generate gray code in js
function  generateGrayarr( n)
{
    var N = 1 << n;
    var result = [];
   
    for ( i = 0; i < N; i++) {
 
        // generate gray code of corresponding
        // binary number of integer i.
        var x = i ^ (i >> 1);
        
 
        // printing gray code
        var r = dec2bin(x);
        
        result.push(pad(n,r));
        
        
    }
           
    console.log(result.join('\n'));
 
}

generateGrayarr(2);
Posted in Cocktail by .

About Gowri

I am professional web developer with 8+ years experience. PHP, jQuery, WordPress, Angular and Ionic are my key skills in web development. I am working with strong enthusiastic team with spirit. We provide all web related solution like HTML/CSS development, Web graphic design and Logo.