Gray code
Order all n-bit strings so that any two neighbours differ in exactly one bit, by reflecting the previous list.
In ordinary binary counting several bits sometimes change at once (0111 → 1000). In a Gray code any two
consecutive numbers differ in one bit only. It is used in rotary encoders, Karnaugh maps and the Tower of Hanoi.
- Time:
O(n · 2ⁿ) - Space:
O(n · 2ⁿ) - Grimaldi, chapter 11
- Johnsonbaugh, chapter 6
The 3-bit Gray code: 000, 001, 011, 010, 110, 111, 101, 100.
def gray_code(n):codes = [""]for size in range(1, n + 1):reflected = codes[::-1]codes = ["0" + c for c in codes] + ["1" + c for c in reflected]rows = []for i in range(len(codes)):# The same code from the formula i XOR (i >> 1), written in n bits.formula = format(i ^ (i >> 1), "b").zfill(n) if n > 0 else ""rows.append((i, codes[i], formula))return codes
Start
The table is still empty.
Local variables
Orange = changed in this step
Call stack
- gray_code()line 1
Explanation
The idea
In ordinary binary counting several bits sometimes change at once (0111 → 1000). In a Gray code any two
consecutive numbers differ in one bit only. It is used in rotary encoders, Karnaugh maps and the Tower of Hanoi.
Building it by reflection
- Write the list of
k-bit codes. - Once with
0in front of each code, then the list reversed with1in front.
In the middle of the new list two equal codes (differing only in the first bit) meet, so the one-bit property is kept.
A direct formula
Code number i is i XOR (i >> 1); the last column of the table shows it, to compare with the reflection method.