Reputation: 51
I have to hash 900 random integers into an empty table that has a set size of 1009 using open addressing. To determine where the number should go in the table I take the random number mod 1009 and then place the number there if it is open. If not I should check the next key after that and keep checking one by one until I find an open one to place the random number. The code I have so far is this:
import java.util.*;
public class openAdd{
public static void main(String[] args) {
//set table length
int[] table = new int[1009];
//insert 900 random integers into the table using open addressing
//random number % table size = the key the number should be placed
//if the key is already taken go to the next key until you find an open one
Random randomGenerator = new Random();
for (int i = 0; i < 900; i++) {
int num = randomGenerator.nextInt(99999);
int key = num % 1009;
if (table[key] == 0) {
table[key] = num;
}
}
}
}
I think what I have so far is good I am just confused on how to go about setting the key to key + 1 if there is already something in the original key. Thank you for your help, and just let me know if I need to add anything.
Upvotes: 2
Views: 173
Reputation: 29680
You seem to have the right idea, just not the right implementation. If table[key]
is nonzero, then you need to increment key
until you find an index in table
where table[key]
is zero. You can utilize Java's remainder operator (like you already are) to prevent key
from increasing over the bound of the array:
int key = num % 1009;
if (table[key] == 0) {
table[key] = num;
} else {
while (table[key = (key + 1) % table.length] != 0);
table[key] = num;
}
Because table.length
is greater than the amount of elements you're setting, there's no need to check if the array is full. Also, keep in mind that num
can be 0
.
Upvotes: 1