I need to make a random number generator that I will be using for student id's.
when the number is generated I want to put it in a hashtable. Its getting the random number fine but its not inserting into the table correctly.
example if the random number is 519 it goes into the first position on the hashtable instead of the 9th and when I try search for the number its tells me its not in the table.
Heres the code for insert:
1 2 3 4 5 6 7 8 9 10 11 12
void HashTable::InsertItem(int item) //insert item into Hash table
{
idNum = item;
srand( (unsigned)time( NULL ) );
item = rand()%999+1;
std::cout << "The student number is: " << item << std::endl;
int location = Hash();
while (hashtable[location] != Empty && hashtable[location] != deleted)
location = (location + 1) % MAX_ITEMS;
hashtable[location] = item;
}
and all I have in main for this code is:
1 2 3 4 5 6 7 8
case 3:
//insert items into hash table
Table.InsertItem(item);
cin.get(); cin.get();
break;
Shouldn't Hash() have some parameter concerning the item it is trying to store? If there is no link between the item and its hash key, how will you find it?
Also, what's the value of MAX_ITEMS? If it's 10 (or one of a select number of possible values), then the behaviour is correct: 519 + 1 = 520, 520%10 = 0 -> items goes into first slot.
idNum is the random number i want to make. heres the code for hash()
1 2 3 4
int HashTable::Hash(void)
{
return (idNum % MAX_ITEMS);
}
it was fine before i added the random number code. MAX_ITEMS is 100
and the numbers are not going onto the hash table correctly they are just appearing one after the other no matter what the number is
Barring very specific circumstances, srand should be called exactly once (typically at program startup). Putting it before every call to rand defeats the entire point.