Say we have the lexicographicaly integers 3,5,6,9,10,12 or 0011,0101,0110,1001,1010,1100
Each with two bits set.
What I want is to find the distance(how
If a
and b
are the positions of the two set bits, with zero being the least significant position, and a
always being greater than b
, then you can calculate:
n = a*(a-1)/2 + b
and the distance between two values is the difference between the two n
values.
Example:
3->12:
3: a1=1, b1=0, n1=0
12: a2=3, b2=2, n2=5
answer: n2-n1 = 5
To extend this to other hamming weights, you can use this formula:
n = sum{i=1..m}(factorial(position[i])/(factorial(i)*factorial(position[i]-i)))
where m
is the hamming weight, and position[i] is the position of the i
'th set bit, counting from the least significant bit, with the least significant set bit's position being position[1]
.