How do I generate random integers within a specifi

2020-01-22 10:52发布

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`.

30条回答
smile是对你的礼貌
2楼-- · 2020-01-22 11:20

Another option is just using Apache Commons:

import org.apache.commons.math.random.RandomData;
import org.apache.commons.math.random.RandomDataImpl;

public void method() {
    RandomData randomData = new RandomDataImpl();
    int number = randomData.nextInt(5, 10);
    // ...
 }
查看更多
别忘想泡老子
3楼-- · 2020-01-22 11:22

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:

Random rn = new Random();
int result = rn.nextInt(max - min + 1) + min;
System.out.println(result);
查看更多
劫难
4楼-- · 2020-01-22 11:22

Just use the Random class:

Random ran = new Random();
// Assumes max and min are non-negative.
int randomInt = min + ran.nextInt(max - min + 1);
查看更多
我只想做你的唯一
5楼-- · 2020-01-22 11:23

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.

查看更多
Bombasti
6楼-- · 2020-01-22 11:24

You can edit your second code example to:

Random rn = new Random();
int range = maximum - minimum + 1;
int randomNum =  rn.nextInt(range) + minimum;
查看更多
Evening l夕情丶
7楼-- · 2020-01-22 11:24

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 reach Integer.MAX_VALUE.
  • (max - min) may cause overflow when min 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:

int nextIntInRange(int min, int max, Random rng) {
   if (min > max) {
      throw new IllegalArgumentException("Cannot draw random int from invalid range [" + min + ", " + max + "].");
   }
   int diff = max - min;
   if (diff >= 0 && diff != Integer.MAX_VALUE) {
      return (min + rng.nextInt(diff + 1));
   }
   int i;
   do {
      i = rng.nextInt();
   } while (i < min || i > max);
   return i;
}

Although inefficient, note that the probability of success in the while loop will always be 50% or higher.

查看更多
登录 后发表回答