From Wolfram MathWorld, we have:

"A Gray code is an encoding of numbers so that adjacent numbers have a single digit differing by 1. The term Gray code is often used to refer to a "reflected" code, or more specifically still, the binary reflected Gray code (...). The code is called reflected because it can be generated in the following manner. Take the Gray code 0, 1. Write it forwards, then backwards: 0, 1, 1, 0. Then prepend 0s to the first half and 1s to the second half: 00, 01, 11, 10. Continuing, write 00, 01, 11, 10, 10, 11, 01, 00 to obtain: 000, 001, 011, 010, 110, 111, 101, 100, ..."

Therefore, to obtain the n-th string, must know all the previous strings. Is there a mathematical formula that can return the nth string without knowing the first n-1 strings?

Thank you very much.

  • 1
    $\begingroup$ The Wikipedia article on Gray code describes the algorithm you want. $\endgroup$ – MJD Oct 31 '14 at 12:26
  • $\begingroup$ Here's a direct link to the (non-recursive) algorithm on Wikipedia. $\endgroup$ – Snowball Oct 31 '14 at 14:21
  • $\begingroup$ But these algorithms require the knowledge of previous strings $\endgroup$ – Mark Oct 31 '14 at 23:40
  • 3
    $\begingroup$ @Mark: The algorithm binaryToGray from the section of the Wikipedia article I linked to gives the $n^{\text{th}}$ entry in the binary reflected Gray code with no reference to previous entries. The only parameter is $n$ (well, num), and it operates in constant time. $\endgroup$ – Snowball Nov 6 '14 at 0:57
  • $\begingroup$ Here's the formula in mathematical notation rather than C: Suppose you want to find the $n^{\text{th}}$ entry in the binary reflected Gray code. Write $n = (b_k b_{k-1} \cdots b_1)_2$ where $b_i$ are the digits of $n$ in binary. Then the corresponding Gray code entry is $(0, b_k, \ldots, b_3, b_2) + (b_k, b_{k-1}, \ldots, b_2, b_1)$, where addition is done elementwise modulo 2. $\endgroup$ – Snowball Nov 6 '14 at 1:04

The same MathWorld article you link has

To convert a binary number $d_1d_2\ldots d_{n-1}d_n$ to its corresponding binary reflected Gray code, start at the right with the digit $d_n$ (the $n$th, or last, digit). If the $d_{n-1}$ is $1$, replace $d_n$ by $1-d_n$; otherwise, leave it unchanged. Then proceed to $d_{n-1}$. Continue up to the first digit $d_1$, which is kept the same since $d_0$ is assumed to be a $0$. The resulting number $g_1g_2\ldots g_{n-1}g_n$ is the reflected binary Gray code.


Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.