Question

This is the question:

Uses open addressing by double hashing, and the main hash function is hi(x) = (hash(x) + f(i)) mod M, where hash(x) = x mod M and f(i) = i ∗ hash2(x) and hash2(x) = 13 − (x mod 7).

I need to INSERT the keys 27, 22, 16, 26, 47, 12, 42, 3 (in this order). The set is the size of 10

This is what i have so far:
0 []
1 []
2 [22]
3 []
4 []
5 []
6 [16]
7 [27]
8 []
9 []

I am confused on inserting 26 because it is a double collsion....Can anyone explain how to do it and what is going on?

Was it helpful?

Solution

Running the risk of showing my ignorance, how is i and M defined? I would guess M to be equal to size and would have guessed i to be a counter for number of insertions, but that wouldn't add up to your output. My implementation however does not collide on 26 but on 42, which means it used more than half the keyspace before getting a collision.


But then I realised specifying i like that would make the position dependant on insertion order.

At that point I had already answered but panicked and removed it, can't look stupid on the Internet, the Internet never forgets. But then I started thinking that maybe I had the wrong idea about the hashing, maybe the numbers are not separate units but part of something that is hashed as a whole, and then the order dependence is correct.

Could someone improve on my wild guesswork?


Ok, lets unroll this then.

hash(x) = x % M
hash2(x) = 13 - (x % 7)
f(i) = i * hash2(x)
hi(x) = (hash(x) + f(i)) % M

for: i=0, M=10, x=27

hash(x) = 27 % 10 -> 7
hash2(x) = 13 - (27 mod 7) -> 7
f(i) = 0 * 7 - > 0
hi(x) = (7 + 0) % 10 -> 7

for: i=1, M=10, x=22

hash(x) = 22 % 10 -> 2
hash2(x) = 13 - (22 mod 7) -> 12
f(i) = 1 * 12 - > 12
hi(x) = (12 + 12) % 10 -> 4

for: i=2, M=10, x=16

hash(x) = 16 % 10 -> 6
hash2(x) = 13 - (16 mod 7) -> 11
f(i) = 2 * 11 - > 22
hi(x) = (6 + 22) % 10 -> 8

and so on, as you can see it diverges quite quickly from what you had

OTHER TIPS

I have a doubt in what r_ahlskog has suggessted. Shouldn't we be incrementing i only when there is a collision. Since 26 ends up in collision, we should increment i t0 1, and at this time 26 gets resolved to slot m=4.

    M = 10 (no. of slots)   
    hi(x) = (hash(x) + f(i)) mod M   (6+0) mod 10 = 14 mod 10 = 6
                                    (6+8) mod 10 = 14 mod 10 = 4
    hash(x) = x mod M                      26 mod 10 = 6

    f(i) = i ∗ hash2(x)           (i=0)  0 * 8 = 0
                                          (i=1) 1 * 8 = 8

    hash2(x) = 13 − (x mod 7)             13 - (26 mod 7) = 13-5=8

hi(x) comes to be 6 for i=0 and for i=1 its 4.

Correct if my understanding wrong.

Here is the final answer --

[0]=12;
[1]=42;
[2]=22;
[3]=3;
[4]=26;
[5]=47;
[6]=16;
[7]=27;

Slots 8 and 9 are free.

Collision happened for 42 as well. This has been resolved at i=3.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top