Open In App

JavaScript Program to Generate n-bit Gray Codes

Last Updated : 21 Sep, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

In this article, we are going to learn about Generate n-bit Gray Codes in JavaScript.Generating n-bit Gray Codes in JavaScript means creating a sequence of binary numbers of length n where each adjacent number differs by only one bit, typically starting with 0 and 1.

There are several methods that can be used to Generate n-bit Gray Codes in JavaScript, which are listed below:

  • Using bitwise XOR and right-shifting operations
  • Using Recursive

We will explore all the above methods along with their basic implementation with the help of examples.

Approach 1: Using bitwise XOR and right-shifting operations

In this approach, we generate n-bit Gray Codes efficiently by performing bitwise XOR and right-shifting operations, creating a sequence of binary numbers that differ in only one bit from their predecessors.

Syntax:

a ^ b  // XOR operator
a>>b // right-shift

Example: In this example, The GrayCodeBit function generates n-bit Gray Codes using bitwise operations and returns them as binary strings. It then iterates through and prints the generated Gray Codes for a specified bit length (n).

Javascript




function GrayCodeBit(n) {
    const resultCode = [];
    for (let i = 0; i < 1 << n; i++) {
        resultCode.push(i ^ (i >> 1));
    }
    return resultCode.map((code) =>
        code.toString(2).padStart(n, '0'));
}
  
// Change this to generate n-bit Gray Codes
const n = 2;
const resultCode = GrayCodeBit(n);
  
for (const code of resultCode) {
    console.log(code);
};


Output

00
01
11
10

Approach 2: Using Recursive function

The recursive approach, represented by the GrayCode function, generates n-bit Gray Codes by building upon smaller code sequences through recursion and bitwise operations, returning an array of Gray Codes.

Syntax:

function GrayCode(n) {
for (let i = 0; i < code1.length; i++) {
}
return;
};

Example: In this example, the GrayCode function generates n-bit Gray Codes recursively. For n=0, it returns [‘0’], and for n=1, it returns [‘0’, ‘1’]. For n>1, it combines previous sequences using bitwise operations and returns an array of Gray Codes.

Javascript




function GrayCode(n) {
    return n === 0
        ? ['0']
        : n === 1
            ? ['0', '1']
            : (() => {
                let code1 = GrayCode(n - 1);
                let resultCode = [];
                for (let i = 0; i < code1.length; i++) {
                    resultCode[i] =
                        '0' + code1[i];
                    resultCode[2 ** n - 1 - i] =
                        '1' + code1[i];
                }
                return resultCode;
            })();
}
  
// Change this to generate n-bit Gray Codes
let n = 2;
let result = GrayCode(n);
console.log(result);


Output

[ '00', '01', '11', '10' ]


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads