Skip to content

feat: added Gray Code algorithm #1425

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 7 commits into from
Oct 8, 2023
Merged
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions Bit-Manipulation/GrayCodes.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
/**
* Generates a Gray code sequence for the given number of bits.
* @param {number} n - The number of bits in the Gray code sequence.
* @returns {string[]} - An array of Gray codes in binary format.
*/
function generateGrayCodes(n) {
if (n <= 0) {
return [0]
}

const grayCodes = [0, 1]

for (let i = 1; i < n; i++) {
const highestBit = 1 << i
for (let j = grayCodes.length - 1; j >= 0; j--) {
grayCodes.push(highestBit | grayCodes[j])
}
}

return grayCodes
}

export { generateGrayCodes }
43 changes: 43 additions & 0 deletions Bit-Manipulation/test/GrayCodes.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import { generateGrayCodes } from '../GrayCodes.js'

/**
* Test cases for the generateGrayCodes function.
*/

test('Generate Gray codes for n=3', () => {
const n = 3
const expectedGrayCodes = [0, 1, 3, 2, 6, 7, 5, 4]
const grayCodes = generateGrayCodes(n)
expect(grayCodes).toEqual(expectedGrayCodes)
})
test('Generate Gray codes for n=0', () => {
const n = 0;
const expectedGrayCodes = [0];
const grayCodes = generateGrayCodes(n);
expect(grayCodes).toEqual(expectedGrayCodes);
});

test('Generate Gray codes for n=1', () => {
const n = 1;
const expectedGrayCodes = [0, 1];
const grayCodes = generateGrayCodes(n);
expect(grayCodes).toEqual(expectedGrayCodes);
});

test('Generate Gray codes for n=4', () => {
const n = 4;
const expectedGrayCodes = [
0, 1, 3, 2, 6, 7, 5, 4, 12, 13, 15, 14, 10, 11, 9, 8
];
const grayCodes = generateGrayCodes(n);
expect(grayCodes).toEqual(expectedGrayCodes);
});

test('Generate Gray codes for n=5', () => {
const n = 5;
const expectedGrayCodes = [
0, 1, 3, 2, 6, 7, 5, 4, 12, 13, 15, 14, 10, 11, 9, 8, 24, 25, 27, 26, 30, 31, 29, 28, 20, 21, 23, 22, 18, 19, 17, 16
];
const grayCodes = generateGrayCodes(n);
expect(grayCodes).toEqual(expectedGrayCodes);
});