To generate a random integer between min
and max
, inclusive, you can use the following formula:
int num = min + (int)(rn * (max - min + 1));
Here’s how it works:
Math.random()
generates a double between 0.0 (inclusive) and 1.0 (exclusive).- Multiplying it by
(max - min + 1)
scales it to be in the range of 0 to(max - min + 1)
(exclusive). - When you cast this result to an integer, it effectively gives you a value in the range
[0, max - min]
. - Finally, adding
min
shifts this range up to[min, max]
.
So the complete line to replace the /* missing code */
would be:
int num = min + (int)(rn * (max - min + 1));
This ensures that num
is uniformly distributed over the integers from min
to max
, including both endpoints.