vaultDweller, you shouldn't use
rand()
to generate random numbers, because it is an outdated function. See this article:
http://cpp.indi.frih.net/blog/2014/12/the-bell-has-tolled-for-rand/
Instead, use the Mersenne Twister. Here's an example of how to use it:
http://www.cplusplus.com/reference/random/mersenne_twister_engine/operator%28%29/
Chervil has the correct formula for random number generation. In order to generate a random number between min and max inclusive, use
unsigned randomNumber = ( generator() % (max - min + 1) ) + min;
(If you named your std::mt19937 object "generator", that is.)
Here's why this formula is the way it is. If you just use
generator();
on its own, without using the modulus operator, or subtracting anything, it will generate a random 32-bit integer (that is, there are 2^32 possible numbers it can generate). But you want random numbers in a certain range, so you use
generator() % max;
. This gives you random numbers in the range from 0 to max-1, since the modulus operator returns the remainder of the random number divided by max, in this example (if you don't know how modulus works, go learn how it works, then come back to this).
If you want max to be inclusive, then write
generator() % (max + 1);
. Now, this will generate random numbers in the range from 0 to max. But, now you want a minimum. It might seem simple enough to add min to the entire thing. Your code is now
( generator() % (max + 1) ) + min;
.
But, you aren't done! This code now generates random numbers in the range min to max + min. Instead of only shifting the minimum up by min, you've shifted the
entire range up by min. We need to correct for this in the code, by doing this:
( generator() % (max - min + 1) ) + min;
Now, this is correct. Notice that the term
max - min + 1
is the
width of the range of numbers. For example, if max is 15, and min is 10, max - min + 1 is 6, the number of numbers inbetween 10 and 15, including 10 and 15. So, we are first restricting the range of random numbers to a certain length, and then shifting this whole range up by min, so that the lowest possible value is min, and the highest possible value is max. Try this out on a number line if you can't understand the explanation in text.
EDIT: I can't believe std::uniform_int_distribution slipped my mind. That is probably a lot easier to use than std::mt19937, for your purposes. Here's an example for how to use it:
http://www.cplusplus.com/reference/random/uniform_int_distribution/operator%28%29/