如何在特定范围内生成随机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`.

当前回答

假设您希望范围在0-9之间,0是最小值,9是最大值。以下函数将打印0到9之间的任何内容。所有范围都一样。

public static void main(String[] args) {
    int b = randomNumberRange(0, 9);
    int d = randomNumberRange (100, 200);
    System.out.println("value of b is " + b);
    System.out.println("value of d is " + d);
}

public static int randomNumberRange(int min, int max) {
    int n = (max + 1 - min) + min;
    return (int) (Math.random() * n);
}

其他回答

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

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

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

有一个图书馆在https://sourceforge.net/projects/stochunit/用于处理范围的选择。

StochIntegerSelector randomIntegerSelector = new StochIntegerSelector();
randomIntegerSelector.setMin(-1);
randomIntegerSelector.setMax(1);
Integer selectInteger = randomIntegerSelector.selectInteger();

它具有边缘包含/排除。

我已经创建了一个方法来获取给定范围内的唯一整数。

/*
      * minNum is the minimum possible random number
      * maxNum is the maximum possible random number
      * numbersNeeded is the quantity of random number required
      * the give method provides you with unique random number between min & max range
*/
public static Set<Integer> getUniqueRandomNumbers( int minNum , int maxNum ,int numbersNeeded ){

    if(minNum >= maxNum)
        throw new IllegalArgumentException("maxNum must be greater than minNum");

    if(! (numbersNeeded > (maxNum - minNum + 1) ))
        throw new IllegalArgumentException("numberNeeded must be greater then difference b/w (max- min +1)");

    Random rng = new Random(); // Ideally just create one instance globally

    // Note: use LinkedHashSet to maintain insertion order
    Set<Integer> generated = new LinkedHashSet<Integer>();
    while (generated.size() < numbersNeeded)
    {
        Integer next = rng.nextInt((maxNum - minNum) + 1) + minNum;

        // As we're adding to a set, this will automatically do a containment check
        generated.add(next);
    }
    return generated;
}
 rand.nextInt((max+1) - min) + min;

在java-8中,他们在Random类中引入了方法int(int randomNumberOrigin,int randomNumber Bound)。

例如,如果要生成[0,10]范围内的五个随机整数(或单个整数),只需执行以下操作:

Random r = new Random();
int[] fiveRandomNumbers = r.ints(5, 0, 11).toArray();
int randomNumber = r.ints(1, 0, 11).findFirst().getAsInt();

第一个参数仅指示生成的IntStream的大小(这是生成无限IntStream的重载方法)。

如果需要执行多个单独的调用,可以从流中创建无限基元迭代器:

public final class IntRandomNumberGenerator {

    private PrimitiveIterator.OfInt randomIterator;

    /**
     * Initialize a new random number generator that generates
     * random numbers in the range [min, max]
     * @param min - the min value (inclusive)
     * @param max - the max value (inclusive)
     */
    public IntRandomNumberGenerator(int min, int max) {
        randomIterator = new Random().ints(min, max + 1).iterator();
    }

    /**
     * Returns a random number in the range (min, max)
     * @return a random number in the range (min, max)
     */
    public int nextInt() {
        return randomIterator.nextInt();
    }
}

您也可以对双值和长值执行此操作。