0

I understand Gray codes have one bit change between them and how to convert between binary and gray. But given a bit length of n, I want to generate a series of Gray codes (all possible) that have one bit change and have maximum k ones.
Example: Given n = 3 and k = 2
001 011 010 110 100 101

PSK
  • 5
  • 6
  • I found a similar problem [here](http://stackoverflow.com/questions/30085584/gray-code-for-all-k-element-subset-of-1-n) but I don't fully understand the answer given by @sh1 and it is not exactly what I need so I opened a new question – PSK Sep 05 '15 at 06:45
  • 1
    I don't think this is possible. The example you gave fails the cyclic property of Gray codes because two bits have to change when rolling around from `101` back to `000`. For other other combinations like n=5 and k=2, it would only be possible to include a small subset of all numbers with no more than k bits set. – r3mainer Sep 05 '15 at 08:54
  • Ahh yes sorry ... What if I were to exclude that combination? I'll edit the question thanks @squeamishossifrage – PSK Sep 05 '15 at 10:19
  • Both `000` and `111` are allowed if starting from `001`. What is the rule to exclude them? Isn't it contradicting `all possible` rule? I understand `k` as maximum allowed differences between initial element and any element in the sequence. – MirMasej Sep 05 '15 at 10:56
  • @MirMasej `k` is the maximum number of one in the bitstring. `111` has `3` ones and if we include `000` cyclic gray codes may not be possible as mentioned. – PSK Sep 05 '15 at 13:15

2 Answers2

1

One possible solution I can think of which is quite different from Gray code generation would be in general:

  • generate all numbers within k (Hamming distance)
  • generate all possible valid combinations of above and pick the longest one(s).

But I don't like it because, you need to store all the numbers in a Set and use try and error.

MirMasej
  • 1,592
  • 12
  • 17
1

I don't believe that it is possible to devise such a code. Here's an informal outline of a proof for the case n=4, k=2. There will be 4 codes with 1 bit set and 6 with 2 bits set.

Start with 0000 (though I don't think it matters where the coding actually starts since a Gray code wraps round). Then the next code will have 1 bit set. The next in sequence must have 2 bits set, the one after that 1 bit, then 2, then 1, then 2, then 1, then 2, and you still have 2 codes with 2 bits set left ...

High Performance Mark
  • 77,191
  • 7
  • 105
  • 161
  • Ahh I see.... but it is definitely interesting to look at what we could do to have least possible changed bits between consecutive codes. It is no longer gray then though Thanks – PSK Sep 05 '15 at 13:52