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]
.
Having a number
x = 2k1+2k2+...+2km
where k1<k2<...<km
it could be claimed that position of number x in lexicographically ordered sequence of all numbers with the same hamming weight is
lex_order(x) = C(k1,1)+C(k2,2)+...+C(km,m)
where C(n,m) = n!/m!/(n-m)! or 0 if m>n
Example:
3 = 20 + 21
lex_order(3) = C(0,1)+C(1,2) = 0+0 = 0
5 = 20 + 22
lex_order(5) = C(0,1)+C(2,2) = 0+1 = 1
6 = 21 + 22
lex_order(6) = C(1,1)+C(2,2) = 1+1 = 2
9 = 20 + 23
lex_order(9) = C(0,1)+C(3,2) = 0+3 = 3