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

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

    It isn't that tough to construct a mapping:

       1  2  3  4  5  use this mapping if (a,b) != (b,a)
    1  0  1  3  6 10
    2  2  4  7 11 16
    3  5  8 12 17 23
    4  9 13 18 24 31
    5 14 19 25 32 40
    
       1  2  3  4  5 use this mapping if (a,b) == (b,a) (mirror)
    1  0  1  2  4  6
    2  1  3  5  7 10
    3  2  5  8 11 14
    4  4  8 11 15 19
    5  6 10 14 19 24
    
    
        0  1 -1  2 -2 use this if you need negative/positive
     0  0  1  2  4  6
     1  1  3  5  7 10
    -1  2  5  8 11 14
     2  4  8 11 15 19
    -2  6 10 14 19 24
    

    Figuring out how to get the value for an arbitrary a,b is a little more difficult.

提交回复
热议问题