For a communication system, I need a special kind of gray codes. The requirements are:
- Two successive values differ in only one bit, like all gray codes.
- Two transitions on the same bit should be at least distant of some arbitrary number of values. this distance is noted mrl for minimum run length.
- I don't care about the distance form the last code to the first code, there is no constraint on the mrl when the code roll-over.
One example of such Gray code is, for 5 bits and mrl = 4:
01111000011110000111100001111000
00111100000011111100001111110000
00011110000111100001111000011110
00001111110000111111000000111100
00000000111111110000000011111111
This paper give the best mrl values for different number of bits. Howerver, those values are found "By use of exhaustive computer searches"
I have python code that work well for small number of bits, up to 6:
N = 5 # number of bit
mrl = 4 # minimum run length
first_transition = [0]
first_code = [0]
def Recur(previous_transitions, previous_codes):
if len(previous_codes) == (2**N):
for b in xrange(N):
print ''.join([str((code >> (N-b-1)) & 1) for code in previous_codes])
print
return
new_transition_list = range(N)
for new_transition in new_transition_list:
ok = True
for i in xrange(mrl-1): #look back for transitions that are too close
try:
if new_transition == previous_transitions[-1-i]:
ok = False
break
except: break
if ok:
new_code = previous_codes[-1] ^ 2**new_transition #look back for repeated code
if not (new_code in previous_codes):
Recur(previous_transitions+[new_transition], previous_codes+[new_code])
Recur(first_transition, first_code )
raw_input('[end]')
My problem is that I would like a code of 20 bits, and the complexity of the basic approach seems close to O(n^3). Any suggestions on how to improve this code? Is there a better approach?
x ^ (x >> 1)
for linearly increasingx
. I have no idea how to modify that to fit your constraints. – Pileous