Good Hash function with 2 integer for a special key

11,349

Go for N'ary numerical system, where N is the maximum possible value of the number in pair.

Like this:

hash(a, b) = a + b * N

then

a = hash(a, b) % N
b = hash(a, b) / N

This will guarantee that for every pair (a, b) there is its own unique hash(a, b). Same things happens to numbers in decimal: imagine all numbers from 0 (we write them as 00, 01, 02, ...) to 99 inclusive are your pairs ab. Then, hash(a, b) = a * 10 + b, and visa-versa, to obtain first digit you have to divide the number by 10, second - get it modulo 10.

Why can't we pick any N, maybe smaller than the maximum of a/b? The answer is: to avoid collision.
If you pick any number and it happens to be smaller than your maximum number, it is highly possible that same hash function will be provided by different pairs of numbers. For example, if you pick N = 10 for pairs: (10, 10) and (0, 11), both their hashes will be equal to 110, which is not good for you in this situation.

Share:
11,349
Chen Li
Author by

Chen Li

Updated on August 21, 2022

Comments

  • Chen Li
    Chen Li almost 2 years

    I'm trying to determine a key for map<double, double> type. But the problem is that the key I want will be generated by a pair of 2 numbers. Are there any good functions which could generate such key for pairs like (0, 1), (2, 3), (4, 2) (0, 2), etc.

    • pilotcam
      pilotcam over 11 years
      See this similar question: stackoverflow.com/questions/2634690/…
    • tenfour
      tenfour over 11 years
      Why not just use std::pair<int, int> as your key type?
    • andre
      andre over 11 years
      yeah, std::map<std::pair<int, int>, int> would be effective.
  • Chen Li
    Chen Li over 11 years
    So something like this: pair (1, 3) = hash(1, 3) = 1 + (3*181.312)
  • dreamzor
    dreamzor over 11 years
    If 181.312 == 181312 == 181 thousand plus 312 and that's your N then yes, this is right. :)
  • Chen Li
    Chen Li over 11 years
    why do I need to keep track of N, can't I use any arbitrary number? But, I'll multiply every entry with the same number