Chen Li - 1 month ago 5

C++ Question

I'm trying to determine a key for

`map<double, double>`

Answer

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 (11, 0), both their hashes will be equal to 110, which is not good for you in this situation.