random number generator

Feb 27, 2012 at 11:53am
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;
Last edited on Feb 27, 2012 at 11:54am
Feb 27, 2012 at 12:27pm
What is idNum and what does Hash() return?
Feb 27, 2012 at 1:18pm
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.
Last edited on Feb 27, 2012 at 1:20pm
Feb 27, 2012 at 4:25pm
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
Last edited on Feb 27, 2012 at 4:29pm
Feb 27, 2012 at 4:28pm
don't call srand before every call to rand.

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.
Feb 28, 2012 at 12:54pm
I got that code from the internet. So what should the code be?
Feb 28, 2012 at 12:56pm
call srand once in your main()
Feb 28, 2012 at 1:18pm
Hi

This topic help me a lot in developing my project. I will contribute more when I finished it.
If you want to get more materials that related to this topic, you can visit:http://interviewquestionsandanswers.biz/case-manager-interview-questions/


Best regards.
Last edited on Mar 3, 2012 at 2:24pm
Feb 28, 2012 at 2:28pm
Topic archived. No new replies allowed.