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`.
Or take a look to RandomUtils from Apache Commons.
Note that this approach is more biased and less efficient than a
nextInt
approach, https://stackoverflow.com/a/738651/360211One standard pattern for accomplishing this is:
The Java Math library function Math.random() generates a double value in the range
[0,1)
. Notice this range does not include the 1.In order to get a specific range of values first, you need to multiply by the magnitude of the range of values you want covered.
This returns a value in the range
[0,Max-Min)
, where 'Max-Min' is not included.For example, if you want
[5,10)
, you need to cover five integer values so you useThis would return a value in the range
[0,5)
, where 5 is not included.Now you need to shift this range up to the range that you are targeting. You do this by adding the Min value.
You now will get a value in the range
[Min,Max)
. Following our example, that means[5,10)
:But, this still doesn't include
Max
and you are getting a double value. In order to get theMax
value included, you need to add 1 to your range parameter(Max - Min)
and then truncate the decimal part by casting to an int. This is accomplished via:And there you have it. A random integer value in the range
[Min,Max]
, or per the example[5,10]
:With java-8 they introduced the method
ints(int randomNumberOrigin, int randomNumberBound)
in theRandom
class.For example if you want to generate five random integers (or a single one) in the range [0, 10], just do:
The first parameter indicates just the size of the
IntStream
generated (which is the overloaded method of the one that produces an unlimitedIntStream
).If you need to do multiple separate calls, you can create an infinite primitive iterator from the stream:
You can also do it for
double
andlong
values.Hope it helps! :)
It's better to use SecureRandom rather than just Random.
The
Math.Random
class in Java is 0-based. So, if you write something like this:x
will be between0-9
inclusive.So, given the following array of
25
items, the code to generate a random number between0
(the base of the array) andarray.length
would be:Since
i.length
will return25
, thenextInt( i.length )
will return a number between the range of0-24
. The other option is going withMath.Random
which works in the same way.For a better understanding, check out forum post Random Intervals (archive.org).
Just a small modification of your first solution would suffice.
See more here for implementation of
Random