Determin the lexicographic distance between two integers

后端 未结 2 1458
时光说笑
时光说笑 2021-01-15 00:23

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

2条回答
  •  旧巷少年郎
    2021-01-15 01:04

    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].

提交回复
热议问题