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

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

    Say you have a 32 bit integer, why not just move A into the first 16 bit half and B into the other?

    def vec_pack(vec):
        return vec[0] + vec[1] * 65536;
    
    
    def vec_unpack(number):
        return [number % 65536, number // 65536];
    

    Other than this being as space efficient as possible and cheap to compute, a really cool side effect is that you can do vector math on the packed number.

    a = vec_pack([2,4])
    b = vec_pack([1,2])
    
    print(vec_unpack(a+b)) # [3, 6] Vector addition
    print(vec_unpack(a-b)) # [1, 2] Vector subtraction
    print(vec_unpack(a*2)) # [4, 8] Scalar multiplication
    

提交回复
热议问题