Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I generate random integers within a specific range in Java?

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.

like image 760
user42155 Avatar asked Dec 12 '08 18:12

user42155


People also ask

How do you generate a random value in a range in Java?

There are several ways to generate random number in Java, such as the nextInt() method of the ThreadLocalRandom class, the random() method of the Math class, the nextInt() method of the Random class, the ints() method of the Random class, the nextFloat() method of the Random class and the RandomUtil class, etc.

How do you generate a random number from within a range?

Method 1: Using Math. random() function is used to return a floating-point pseudo-random number between range [0,1) , 0 (inclusive) and 1 (exclusive). This random number can then be scaled according to the desired range.

Can you write a random integers function to print integers within a range?

Above formula will generates a random integer in a range between min (inclusive) and max (inclusive). //Random(). nextInt(int bound) = Random integer from 0 (inclusive) to bound (exclusive) //1. nextInt(range) = nextInt(max - min) new Random().

How can I generate a random number within a range but exclude some?

int i = rand(1, 9); if i>=7 i++; return i; As long as you ensure that your mapping is 1:1, you can avoid skewing the randomness of your rand function. Ax. The other way round would be better: create numbers from1 to 8 and map 7 and 8 to 8 and 9.


1 Answers

In Java 1.7 or later, the standard way to do this is as follows:

import java.util.concurrent.ThreadLocalRandom;  // nextInt is normally exclusive of the top value, // so add 1 to make it inclusive int randomNum = ThreadLocalRandom.current().nextInt(min, max + 1); 

See the relevant JavaDoc. This approach has the advantage of not needing to explicitly initialize a java.util.Random instance, which can be a source of confusion and error if used inappropriately.

However, conversely there is no way to explicitly set the seed so it can be difficult to reproduce results in situations where that is useful such as testing or saving game states or similar. In those situations, the pre-Java 1.7 technique shown below can be used.

Before Java 1.7, the standard way to do this is as follows:

import java.util.Random;  /**  * Returns a pseudo-random number between min and max, inclusive.  * The difference between min and max can be at most  * <code>Integer.MAX_VALUE - 1</code>.  *  * @param min Minimum value  * @param max Maximum value.  Must be greater than min.  * @return Integer between min and max, inclusive.  * @see java.util.Random#nextInt(int)  */ public static int randInt(int min, int max) {      // NOTE: This will (intentionally) not run as written so that folks     // copy-pasting have to think about how to initialize their     // Random instance.  Initialization of the Random instance is outside     // the main scope of the question, but some decent options are to have     // a field that is initialized once and then re-used as needed or to     // use ThreadLocalRandom (if using at least Java 1.7).     //      // In particular, do NOT do 'Random rand = new Random()' here or you     // will get not very good / not very random results.     Random rand;      // nextInt is normally exclusive of the top value,     // so add 1 to make it inclusive     int randomNum = rand.nextInt((max - min) + 1) + min;      return randomNum; } 

See the relevant JavaDoc. In practice, the java.util.Random class is often preferable to java.lang.Math.random().

In particular, there is no need to reinvent the random integer generation wheel when there is a straightforward API within the standard library to accomplish the task.

like image 123
Greg Case Avatar answered Sep 30 '22 10:09

Greg Case