You can create a Gray code for exactly the numbers 0 to n-1, for any n, by the following steps: 1. Create the binary reflected Gray code for the next higher power of 2. 2. Take just the first n numbers of that binary reflected Gray code. 3. Bitwise exclusive-or each of these n numbers in the Gray code with the binary representation of floor(n/2) (i.e., n shifted right by one bit).
To create a cyclic Gray code for exactly the numbers 0 to n-1, n must be even. (It's easy to prove that you cannot get a cyclic Gray code for odd n.) 1. Generate the Gray code for 0 to n/2-1, as above. 2. Concatenate the reflection of that Gray code to itself. 3. Shift each of the n numbers you now have left by one bit. The first half gives you all the even numbers 0 to n-2, with the Gray-code property. 4. Put a 1 in the least significant bit in the second half The second half gives you all the odd numbers 1 to n-1, again with the Gray-code property.
The whole sequence gives you 0 to n-1, with the Gray-code property, and it's cyclic.
If you'd like a PDF of the paper, email me: thc@cs.dartmouth.edu.
Tom Cormen Professor of Computer Science Dartmouth College
Example with 6:
000
100
110
111
101
001
Proof: Adjacent gray codes have hamming distance 1, so the graph of gray codes is cycle on a hypercube. All cycles on a hypercube graph are even, so every sequence of gray codes is even.Or rather, I was about to post about hypercubes and cycles myself :D
All even numbers should be possible though. For example, here is 6 positions: 000, 001, 011, 111, 110, 100 - and this strategy can generalize to any even number.
0110
0010
1010
1011
1111
1101
0101
0111
0011
0001
0000
0100 0000
0001
0011 <
0010 <
0110 <
0111 <
0101 <
0100 <
1100 <
1101 <
1111 <
1110 <
1010 <
1011 <
1001
1000