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

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

    We can encode two numbers into one in O(1) space and O(N) time. Suppose you want to encode numbers in the range 0-9 into one, eg. 5 and 6. How to do it? Simple,

      5*10 + 6 = 56. 
       
        5 can be obtained by doing 56/10 
        6 can be obtained by doing 56%10.
    

    Even for two digit integer let's say 56 and 45, 56*100 + 45 = 5645. We can again obtain individual numbers by doing 5645/100 and 5645%100

    But for an array of size n, eg. a = {4,0,2,1,3}, let's say we want to encode 3 and 4, so:

     3 * 5 + 4 = 19               OR         3 + 5 * 4 = 23
     3 :- 19 / 5 = 3                         3 :- 23 % 5 = 3
     4 :- 19 % 5 = 4                         4 :- 23 / 5 = 4
    

    Upon generalising it, we get

        x * n + y     OR       x + n * y
    

    But we also need to take care of the value we changed; so it ends up as

        (x%n)*n + y  OR x + n*(y%n)
    

    You can obtain each number individually by dividing and finding mod of the resultant number.

提交回复
热议问题