Mapping two integers to one, in a unique and deterministic way

前端 未结 19 2442
不知归路
不知归路 2020-11-22 09:35

Imagine two positive integers A and B. I want to combine these two into a single integer C.

There can be no other integers D and E which combine to C. So combining

19条回答
  •  不知归路
    2020-11-22 10:08

    What you suggest is impossible. You will always have collisions.

    In order to map two objects to another single set, the mapped set must have a minimum size of the number of combinations expected:

    Assuming a 32-bit integer, you have 2147483647 positive integers. Choosing two of these where order doesn't matter and with repetition yields 2305843008139952128 combinations. This does not fit nicely in the set of 32-bit integers.

    You can, however fit this mapping in 61 bits. Using a 64-bit integer is probably easiest. Set the high word to the smaller integer and the low word to the larger one.

提交回复
热议问题