Symmetric Bijective Algorithm for Integers

后端 未结 11 860
甜味超标
甜味超标 2020-12-01 03:33

I need an algorithm that can do a one-to-one mapping (ie. no collision) of a 32-bit signed integer onto another 32-bit signed integer.

My real concern is enough entr

11条回答
  •  萌比男神i
    2020-12-01 04:15

    If your goal is simply to get a seemingly random permutation of numbers of a roughly defined size, then there is another possible way: reduce the set of numbers to a prime number.

    Then you can use a mapping of the form

    f(i) = (i * a + b) % p

    and if p is indeed a prime, this will be a bijection for all a != 0 and all b. It will look fairly random for larger a and b.

    For example, in my case for which I stumbled on this question, I used 1073741789 as a prime for the range of numbers smaller than 1 << 30. That makes me lose only 35 numbers, which is fine in my case.

    My encoding is then

    ((n + 173741789) * 507371178) % 1073741789
    

    and the decoding is

    (n * 233233408 + 1073741789 - 173741789) % 1073741789
    

    Note that 507371178 * 233233408 % 1073741789 == 1, so those two numbers are inverse the field of numbers modulo 1073741789 (you can figure out inverse numbers in such fields with the extended euclidean algorithm).

    I chose a and b fairly arbitrarily, I merely made sure they are roughly half the size of p.

提交回复
热议问题