First:
srand()
should not be called more than once! Take it out of the populate function.
Now:
RAND_MAX defined the maximum number that is generated. It is guaranteed to be at least 32767 but varies depending on implementation.
Lets consider hexidecimal for a moment. If we get a random number between 0 and 15, but we need a random number between 50 and 60, then we'll need to use more than one digit. Now lets consider a number system with base RAND_MAX. The same rule applies. Therefore this would be the correct way to do this:
1 2 3 4 5 6 7 8 9 10 11 12
|
int SimulationUI::populate(int min, int max)
{
int number = rand();
for (int i = 1; (RAND_MAX+1) * i < (max-min); i++)
{
number *= RAND_MAX+1; // bit-shift
number += rand(); // Populate the lower bits now
}
// number is now a random number between 0 and (RAND_MAX+1)^i. Now filter out values that don't fall within your required range.
return number%(max-min) + min;
}
|
Why?
Let's consider an example where rand() only gives us an output between 0 and 15. In binary RAND_MAX would look like:
0000 1111
So we can see that only the first four bits will be set. After we multiply our random number by RAND_MAX+1 (16 in dec, 0x10 in hex,
0001 0000 in binary) it will be in this range:
1111 0000
So if we add another rand() to it, we'll get a number in this range:
1111 1111
There, we've effectively changed RAND_MAX from 15 to 255. We can make it as large as we like assuming that it will fit in a container.
Oh, and for reference, 32767 looks like this in binary:
0000 0000 0000 0000 0111 1111 1111 1111