Generate a unique value for a combination of two numbers

后端 未结 9 922
有刺的猬
有刺的猬 2020-12-16 16:09

Consider I\'ve two numbers 1023232 & 44. I want to generate a unique number representing this combination of numbers. How can i generate it?

Requirement

9条回答
  •  太阳男子
    2020-12-16 16:38

    You could use the function given here. This is the most space efficient I have seen and also doesn't involve any string approaches. The native function in the link won't work for negative integers though. But you can modify it as shown below to make it work for negative integers.

    This will give back negative results too. For more on it and other options see this SO answer.

    public static long GetHashCode_OrderIrrelevant(int a, int b)
    {
        return GetHashCode(Math.Min(a, b), Math.Max(a, b));
    }
    
    public static long GetHashCode(int a, int b)
    {
        var A = (ulong)(a >= 0 ? 2 * (long)a : -2 * (long)a - 1);
        var B = (ulong)(b >= 0 ? 2 * (long)b : -2 * (long)b - 1);
        var C = (long)((A >= B ? A * A + A + B : A + B * B) / 2);
        return a < 0 && b < 0 || a >= 0 && b >= 0 ? C : -C - 1;
    }
    

提交回复
热议问题