Skip to content

Commit f21e1c4

Browse files
committed
feat:added Gray Code algorithm
1 parent 1de5ab7 commit f21e1c4

File tree

2 files changed

+27
-0
lines changed

2 files changed

+27
-0
lines changed

Bit-Manipulation/GrayCodes.js

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,19 @@
1+
// To generate Gray codes using bit manipulation in JavaScript, we can create a function that takes an integer n as input and returns an array of Gray codes up to 2^n - 1
2+
function generateGrayCodes(n) {
3+
if (n <= 0) {
4+
return [0]
5+
}
6+
7+
const grayCodes = [0, 1]
8+
9+
for (let i = 1; i < n; i++) {
10+
const highestBit = 1 << i
11+
for (let j = grayCodes.length - 1; j >= 0; j--) {
12+
grayCodes.push(highestBit | grayCodes[j])
13+
}
14+
}
15+
16+
return grayCodes
17+
}
18+
19+
export { generateGrayCodes } // Export the function for testing
Lines changed: 8 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,8 @@
1+
import { generateGrayCodes } from '../GrayCodes.js' // Import the function
2+
3+
test('Generate Gray codes for n=3', () => {
4+
const n = 3
5+
const expectedGrayCodes = [0, 1, 3, 2, 6, 7, 5, 4]
6+
const grayCodes = generateGrayCodes(n)
7+
expect(grayCodes).toEqual(expectedGrayCodes)
8+
})

0 commit comments

Comments
 (0)
pFad - Phonifier reborn

Pfad - The Proxy pFad of © 2024 Garber Painting. All rights reserved.

Note: This service is not intended for secure transactions such as banking, social media, email, or purchasing. Use at your own risk. We assume no liability whatsoever for broken pages.


Alternative Proxies:

Alternative Proxy

pFad Proxy

pFad v3 Proxy

pFad v4 Proxy