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

前端 未结 19 2574
不知归路
不知归路 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:04

    f(a, b) = s(a+b) + a, where s(n) = n*(n+1)/2

    • This is a function -- it is deterministic.
    • It is also injective -- f maps different values for different (a,b) pairs. You can prove this using the fact: s(a+b+1)-s(a+b) = a+b+1 < a.
    • It returns quite small values -- good if your are going to use it for array indexing, as the array does not have to be big.
    • It is cache-friendly -- if two (a, b) pairs are close to each other, then f maps numbers to them which are close to each other (compared to other methods).

    I did not understand what You mean by:

    should always yield an integer on either the positive or the negative side of integers

    How can I write (greater than), (less than) characters in this forum?

提交回复
热议问题