|
2 | 2 | * Generates a Gray code sequence for the given number of bits.
|
3 | 3 | *@param {number} n - The number of bits in the Gray code sequence.
|
4 | 4 | *@returns {number[]} - An array of Gray codes in binary format.
|
| 5 | + *@description |
| 6 | + * Gray codes are binary sequences in which two successive values differ in only one bit. |
| 7 | + * This function generates a Gray code sequence of length 2^n for the given number of bits. |
| 8 | + * |
| 9 | + * The algorithm follows these steps: |
| 10 | + * |
| 11 | + * 1. Initialize an array `grayCodes` to store the Gray codes. Start with [0, 1] for n = 1. |
| 12 | + * 2. Iterate from 1 to n: |
| 13 | + * a. Calculate `highestBit` as 2^i, where `i` is the current iteration index. |
| 14 | + * b. Iterate in reverse order through the existing Gray codes: |
| 15 | + * - For each Gray code `code`, add `highestBit | code` to `grayCodes`. |
| 16 | + * - This operation flips a single bit in each existing code, creating new codes. |
| 17 | + * 3. Return the `grayCodes` array containing the Gray codes in decimal representation. |
| 18 | + * |
| 19 | + *resources: [GFG](https://www.geeksforgeeks.org/generate-n-bit-gray-codes/) |
| 20 | + *@example |
| 21 | + * const n = 3; |
| 22 | + * const grayCodes = generateGrayCodes(n); |
| 23 | + * // grayCodes will be [0, 1, 3, 2, 6, 7, 5, 4] for n=3. |
5 | 24 | */
|
6 | 25 | functiongenerateGrayCodes(n){
|
7 | 26 | if(n<=0){
|
|