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

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

    Although Stephan202's answer is the only truly general one, for integers in a bounded range you can do better. For example, if your range is 0..10,000, then you can do:

    #define RANGE_MIN 0
    #define RANGE_MAX 10000
    
    unsigned int merge(unsigned int x, unsigned int y)
    {
        return (x * (RANGE_MAX - RANGE_MIN + 1)) + y;
    }
    
    void split(unsigned int v, unsigned int &x, unsigned int &y)
    {
        x = RANGE_MIN + (v / (RANGE_MAX - RANGE_MIN + 1));
        y = RANGE_MIN + (v % (RANGE_MAX - RANGE_MIN + 1));
    }
    

    Results can fit in a single integer for a range up to the square root of the integer type's cardinality. This packs slightly more efficiently than Stephan202's more general method. It is also considerably simpler to decode; requiring no square roots, for starters :)

提交回复
热议问题