如何在特定范围内生成随机int值?

以下方法存在与整数溢出相关的错误:

randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.
Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum =  minimum + i;
// Bug: `randomNum` can be smaller than `minimum`.

当前回答

要生成“介于两个数字之间”的随机数,请使用以下代码:

Random r = new Random();
int lowerBound = 1;
int upperBound = 11;
int result = r.nextInt(upperBound-lowerBound) + lowerBound;

这将为您提供一个介于1(含)和11(不含)之间的随机数,因此通过添加1来初始化上限值。例如,如果要生成1到10之间的随机数,则使用11而不是10初始化上限数。

其他回答

注意,该方法比下一个Int方法更偏向且效率更低,https://stackoverflow.com/a/738651/360211

实现这一点的一个标准模式是:

Min + (int)(Math.random() * ((Max - Min) + 1))

Java Math库函数Math.random()生成范围[0,1)内的双精度值。请注意,此范围不包括1。

为了首先获得特定的值范围,需要乘以要覆盖的值范围的大小。

Math.random() * ( Max - Min )

这将返回范围[0,Max Min)内的值,其中不包括“Max Min”。

例如,如果需要[5,10),则需要覆盖五个整数值,以便使用

Math.random() * 5

这将返回范围为[0.5)的值,其中不包括5。

现在,您需要将此范围移动到目标范围。您可以通过添加“最小值”值来实现此操作。

Min + (Math.random() * (Max - Min))

现在,您将获得范围为[Min,Max)的值。按照我们的示例,这意味着[5,10):

5 + (Math.random() * (10 - 5))

但是,这仍然不包括Max,您将得到双倍的值。为了获得包含的最大值,您需要向范围参数(Max-Min)添加1,然后通过强制转换为int来截断小数部分。这可以通过以下方式实现:

Min + (int)(Math.random() * ((Max - Min) + 1))

在[Min,Max]范围内的随机整数值,或者按照示例[5,10]:

5 + (int)(Math.random() * ((10 - 5) + 1))

下面是一个函数,它按照用户42155的请求,在lowerBoundIncluded和upperBoundIncluded定义的范围内返回一个整数随机数

SplitableRandom splitableRandom=新的Splitablerandom();

BiFunction<Integer,Integer,Integer> randomInt = (lowerBoundIncluded, upperBoundIncluded)
    -> splittableRandom.nextInt(lowerBoundIncluded, upperBoundIncluded + 1);

randomInt.apply(…,…);//获取随机数

…或更短,用于一次性生成随机数

new SplittableRandom().nextInt(lowerBoundIncluded, upperBoundIncluded + 1);

使用Java 8 IntStream和Collections.shuffle的不同方法

import java.util.stream.IntStream;
import java.util.ArrayList;
import java.util.Collections;

public class Main {

    public static void main(String[] args) {

        IntStream range = IntStream.rangeClosed(5,10);
        ArrayList<Integer> ls =  new ArrayList<Integer>();

        //populate the ArrayList
        range.forEach(i -> ls.add(new Integer(i)) );

        //perform a random shuffle  using the Collections Fisher-Yates shuffle
        Collections.shuffle(ls);
        System.out.println(ls);
    }
}

Scala中的等价项

import scala.util.Random

object RandomRange extends App{
  val x =  Random.shuffle(5 to 10)
    println(x)
}

因为Android的问题在这里重定向,这就是你如何使用Kotlin:

val r = (0..10).random() // A random integer between 0 and 10 inclusive

这适用于Kotlin 1.3及更高版本。请参阅此答案。

我想知道Apache Commons Math库提供的任何随机数生成方法是否符合要求。

例如:RandomDataGenerator.nextInt或RandomDataGenerator.nextLong