In the tutorial about random number generation (Fundamental Data Types - 6), the solution for the dice roll is to execute the rand()function twice like so:
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
const short minValue = 1;
const short maxValue = 6;
srand(time(0));
short first = (rand() % (maxValue - minValue +1)) + minValue;
short second = (rand() % (maxValue - minValue +1)) + minValue;
cout << first << ", " << second;
return 0;
}
It makes no sense to me that first and second would have different values given that
srand(time(0)) is executed only once (where time(0) represents the number of seconds passed since Jan. 1, 1970), so the seed value is also set only once
first and second are set within micro- if not nano-seconds from one another, so it is extremely unlikely for the seed value and thus srand(time(0)) to have changed within that time frame, ergo first and second should always have the same value.
I can’t tell for sure for C and I wanted to compare with C# because there is a situation where I got always the same values in a loop, but it seems they “fixed” this behaviour.
It was that when you use random and create a new Random object un each loop, it actually gave the same number. The solution was to use a Random object outside the loop. But now with .NET 10 it seems giving no difference in term of results.
To me the problem was similar to what you describe. The iterations happen so fast that every instance actually provide the same value.
Random x = new Random(0);
for (int i = 0; i < 10; i++)
{
Console.WriteLine(x.Next());
}
Console.WriteLine(“”);
for (int i = 0; i < 10; i++)
{
Random y = new Random(0);
Console.WriteLine(x.Next());
}
You use srand to kind of initialize the randomizer. (Does the “s” from srand means “set” ?) srand(time(0)) could be equivalent to Random x = new Random(0).
Since then every call to rand() would then be equivalent to x.Next() but you probably don’t see it explicitely with C. So it is indeed using the same object and the same seed but that’s (from my PoV) the best situation possible. No matter how fast the object called, it would likely give random values that differ from one another. There could also be cases where you’d get the same result while there is a few seconds between 2 runs. That happens, especially with such a reduced range.