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

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

    For positive integers as arguments and where argument order doesn't matter:

    1. Here's an unordered pairing function:

       = x * y + trunc((|x - y| - 1)^2 / 4) = 
      
    2. For x ≠ y, here's a unique unordered pairing function:

       = if x < y:
                 x * (y - 1) + trunc((y - x - 2)^2 / 4)
               if x > y:
                 (x - 1) * y + trunc((x - y - 2)^2 / 4)
             = 
      

提交回复
热议问题