How do I generate a random int
value in a specific range?
I have tried the following, but those do not work:
Attempt 1:
randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.
Attempt 2:
Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum = minimum + i;
// Bug: `randomNum` can be smaller than `minimum`.
Another option is just using Apache Commons:
Generate a random number for the difference of min and max by using the nextint(n) method and then add min number to the result:
Just use the Random class:
When you need a lot of random numbers, I do not recommend the Random class in the API. It has just a too small period. Try the Mersenne twister instead. There is a Java implementation.
You can edit your second code example to:
Forgive me for being fastidious, but the solution suggested by the majority, i.e.,
min + rng.nextInt(max - min + 1))
, seems perilous due to the fact that:rng.nextInt(n)
cannot reachInteger.MAX_VALUE
.(max - min)
may cause overflow whenmin
is negative.A foolproof solution would return correct results for any
min <= max
within [Integer.MIN_VALUE
,Integer.MAX_VALUE
]. Consider the following naive implementation:Although inefficient, note that the probability of success in the
while
loop will always be 50% or higher.