I am trying to generate random numbers between 10 and 20. I have used srand(time(0)) and called it once before the for loop. As the program program run faster, the for loop is probably getting same seed. To overcome, I used sleep(1000) for every iteration the rand() is called. I am not expecting all unique values, as it should not be, but I get 1 sec delay. Is there any better approach ? Thank you for reading.
If you use a timer to produce the seed and you call the timer many times within its resolution you'll get the same seed. This means you get the same random sequence over and over again.
So if you want to seed using a timer do it exactly once in the entire program.
Depending on what you're doing it's often better to use a constant seed. Then the results of your program will be reproducable between different runs.
Thank you nuzzle. But I would have explained my question better. I called srand() only once. But still I get all same values. This might be because the program runs faster than the timer to change it's value. So I had tried to delay 1 second using sleep(1000) and the rand() gets a chance to output a new value(not necessarily a new value, but gets a chance). Any other better solution instead of thread sleep?
Last edited by thomus07; December 22nd, 2009 at 04:00 AM.
Sorry nuzzle again, I didn't explain you better.
I removed the sleep finally.
This can give me what I am trying to achieve. It will take a lower limit like 10, and upper limit like 20 and prints it only if it's not already available. I think my problem is solved. If this code has a flaw please get me.
int lower_limit = 0;
int upper_limit = 0;
cout << "Enter lower limit: ";
cin >> lower_limit;
cout << "Enter upper limit: ";
cin >> upper_limit;
while(v_num.size() != (upper_limit - lower_limit)+1 )
int n = lower_limit + rand() % (upper_limit - lower_limit+1);
vector<int>::iterator it = find(v_num.begin(), v_num.end(), n);
if (it == v_num.end())
cout << n << endl;
If you want to generate a random sequence of unique numbers there's a simpler way.
You fill the int vector with the numbers (from say 10 up to 20). Then you call random_shuffle to randomly shuffle it. The ints in the vector will then be in random order. Each time you call random_shuffle you get a new random order. Random_shuffle is part of the C++ STL library like vector.
And it's very efficient. The random shuffle algorithm needs just one pass through the vector.
Your approach is efficient at first when the vector is quite empty but as it fills up the chance increases that a new random number is already in the vector. This culminates when there's just one more number missing. If you want N numbers in the vector, the final number will require N tries on average before the right one is found. And each of these N tries requires one pass through the vector to establish whether the number is already there or not. So it tends to be very slow when N is big.
Last edited by nuzzle; December 22nd, 2009 at 06:55 AM.