Find twelve 32-bit numbers such that each pair of them differs by bits in at least 17 positions.
I'm struggling to find and optimal algorithm for this problem. More general question is: Find 'n' 32-bit numbers such that each pair of them differs by bits in at least 'm' positions.
My first approach was to randomly pick a number or start from any let's say 6 (00000110) and then once again pick other random number. Then make a XOR operation and count how many 1 we have in binary representation of the XOR result which will indicate on how many places the numbers differentiate. If the condition is accepted we can store those two numbers and do the same process until we reach wanted amount of numbers. However such algorithm seems not to be optimal because we are picking random numbers so it could last 'forever'.
*UPDATE I prepared such code and for m = 16 it actually returns 12 results, however for 17 (which I need) it stops at 9 results and code never finishes. I am wondering if it is possible that in [0, 2^32] range there are not such twelve numbers, but how to prove it?
import random
def hamming_distance(x, y):
dist = 0
# The ^ operator sets to 1 only the bits that are different
val = x ^ y
while val > 0:
# We then count the bit set to 1 using the Peter Wegner way
val = val & (val - 1) # Set to zero val's lowest-order 1
dist += 1
# Return the number of differing bits
return dist
def solution(n = 12, m = 17):
result = [0]
while len(result) < n:
r = random.randint(0,2**32)
if all(hamming_distance(r,el) >= m for el in result):
result.append(r)
print(result)
return result
print(solution())