Search code examples
hashhashtableuniversal

Universal hashing, should get the same hash value for the same key?


I mean, I have implemented an universal hashing function using this expression:

h(k) = ((a*k + b)mod p)mod m; (from Cormen)

where: -p is big prime number greater than k; -a and b are two numbers that are randomly choosen the first in the range [1, p-1] and the second one [0, p-1].

Now, I implemented this, and for the random function I have choosen the seed equal to k. That's because, if I don't do this, when I insert a value with the key k, it will generate a hash value, that will depends on the default seed of Random function (maybe the time). So if I want to search the key again, I can't do this, because now the universal hashing function returns me another value. So, I would appreciate you to tell me if my reasoning is correct or not. My doubt is that now, doing so, if two elements have the same key, they will be irrimediably stored in the same linked list (thing that I didn't understand if it is correct or not).

Thanks in advance.


Solution

  • I think you have a slight misunderstanding about how universal hashing works. Rather than choosing a and b at random every time you compute the hash, instead, before you do any hashing at all, select a random a and b. Once you've done that, every time you need to compute the hash, go and compute it using the formula above based on the input value k and the values a and b that you chose initially.