Gamified challenge · Gray code
A dial has n switches, so it shows an n-bit code from 0 to 2^n - 1. It starts at 0, and each click changes exactly one bit.
Write gray(n) that returns the 2^n codes in the order the dial visits them: start at 0, use every code exactly once, change one bit per click, and make the last code one bit away from 0 so the dial can close back to the start. For n = 2, [0, 1, 3, 2] works (00 → 01 → 11 → 10); so does [0, 2, 3, 1]. Any valid order passes.
0 ≤ n ≤ 10. For n = 0 the dial has one code: [0].
This game is part of the paid plans. Sign in, then pick a plan to write your answer, watch it play out, and step through the algorithm with its guide.
Sign in with Google