1. 程式人生 > 其它 >如何在Java的特定範圍內生成隨機整數? [英]How do I generate random integers within a specific range in Java?

如何在Java的特定範圍內生成隨機整數? [英]How do I generate random integers within a specific range in Java?

技術標籤:pythonjava演算法人工智慧資料分析

How do I generate a randomintvalue in a specific range?

如何在特定範圍內生成一個隨機整型值?

I have tried the following, but those do not work:

我試過以下方法,但都沒用:

Attempt 1:

嘗試1:

randomNum = minimum + (int)(Math.random() * maximum);
// Bug: `randomNum` can be bigger than `maximum`.

Attempt 2:

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

59 個解決方案

#1


3211

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

在Java 1.7或更高版本中,實現此目的的標準方法如下:

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);

Seethe relevant JavaDoc. This approach has the advantage of not needing to explicitly initialize ajava.util.Randominstance, which can be a source of confusion and error if used inappropriately.

看到相關的JavaDoc。這種方法的優點是不需要顯式地初始化java.util。隨機例項,如果使用不當,可能會造成混亂和錯誤。

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.

然而,相反地,沒有辦法顯式地設定種子,因此很難在諸如測試或儲存遊戲狀態或類似的情況下重現結果。在這些情況下,可以使用下面所示的java前1.7技術。

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

在Java 1.7之前,實現這一點的標準方法如下:

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;
}

Seethe relevant JavaDoc. In practice, thejava.util.Randomclass is often preferable tojava.lang.Math.random().

看到相關的JavaDoc。在實踐中,java.util。Random類通常比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.

特別是,當標準庫中有一個簡單的API來完成這個任務時,不需要重新建立隨機整數生成輪。

#2


1315

Note that this approach is more biased and less efficient than anextIntapproach,https://stackoverflow.com/a/738651/360211

注意,這種方法比nextInt方法(https://stackoverflow.com/a/738651/360211)更有偏見,效率也更低

One standard pattern for accomplishing this is:

實現這一點的一個標準模式是:

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

TheJavaMath library function Math.random() generates a double value in the range[0,1). Notice this range does not include the 1.

Java數學庫函式Math.random()在範圍[0,1]中生成一個雙值。注意,這個範圍不包括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.

為了首先獲得特定的值範圍,您需要將所覆蓋的值範圍的大小相乘。

Math.random() * ( Max - Min )

This returns a value in the range[0,Max-Min), where 'Max-Min' is not included.

這將返回在[0,Max-Min]範圍內的值,其中不包括'Max-Min'。

For example, if you want[5,10], you need to cover five integer values so you use

例如,如果您想要[5,10],您需要覆蓋五個整數值,以便使用

Math.random() * 5

This would return a value in the range[0,5), where 5 is not included.

這將返回範圍[0,5]中的值,其中不包括5。

Now you need to shift this range up to the range that you are targeting. You do this by adding the Min value.

現在你需要把這個範圍轉移到你的目標範圍。通過增加最小值來實現這一點。

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

You now will get a value in the range[Min,Max). Following our example, that means[5,10):

現在你會得到範圍內的值[最小值,最大值]。以我們為例,這意味著[5,10]:

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

But, this still doesn't includeMaxand you are getting a double value. In order to get theMaxvalue 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:

但是,這個仍然不包含Max你得到了一個雙重值。為了得到包含的最大值,您需要在您的範圍引數(Max - Min)中新增1,然後通過插入到int來截斷小數部分。

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

And there you have it. A random integer value in the range[Min,Max], or per the example[5,10]:

這就是它。範圍內的一個隨機整數值[Min,Max],或每個例子[5,10]:

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

#3


309

Use:

使用:

Random ran = new Random();
int x = ran.nextInt(6) + 5;

The integerxis now the random number that has a possible outcome of5-10.

整數x現在是可能結果為5-10的隨機數。

#4


120

Use:

使用:

minimum + rn.nextInt(maxValue - minvalue + 1)

#5


96

Withjava-8they introduced the methodints(int randomNumberOrigin, int randomNumberBound)in theRandomclass.

在java-8中,他們在隨機類中引入了方法int (int randomNumberOrigin, int randomNumberBound)。

For example if you want to generate five random integers (or a single one) in the range [0, 10], just do:

例如,如果您想在[0,10]範圍內生成5個隨機整數(或單個整數),只需:

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

The first parameter indicates just the size of theIntStreamgenerated (which is the overloaded method of the one that produces an unlimitedIntStream).

第一個引數僅指示生成的IntStream的大小(它是生成無限IntStream的過載方法)。

If you need to do multiple separate calls, you can create an infinite primitive iterator from the stream:

如果需要進行多個獨立呼叫,可以從流中建立一個無限的原始迭代器:

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();
    }
}

You can also do it fordoubleandlongvalues.

你也可以做雙倍和長的數值。

Hope it helps! :)

希望它可以幫助!:)

#6


90

You can edit your second code example to:

您可以將第二個程式碼示例編輯為:

Random rn = new Random();
int range = maximum - minimum + 1;
int randomNum =  rn.nextInt(range) + minimum;

#7


85

Just a small modification of your first solution would suffice.

只要稍微修改一下您的第一個解決方案就足夠了。

Random rand = new Random();
randomNum = minimum + rand.nextInt((maximum - minimum) + 1);

See more here for implementation ofRandom

這裡更多的是為了實現隨機。

#8


53

ThreadLocalRandom equivalent of class java.util.Random for multithreaded environment. Generating a random number is carried out locally in each of the threads. So we have a better performance by reducing the conflicts.

類java.util的ThreadLocalRandom等價。隨機對多執行緒環境。在每個執行緒中本地生成隨機數。通過減少衝突,我們有更好的表現。

int rand = ThreadLocalRandom.current().nextInt(x,y);

x,y - intervals e.g. (1,10)

x,y -區間(1,10)

#9


51

TheMath.Randomclass inJavais 0-based. So, if you write something like this:

的數學。Java中的Random類是基於0的。如果你這樣寫:

Random rand = new Random();
int x = rand.nextInt(10);

xwill be between0-9inclusive.

x在0-9之間。

So, given the following array of25items, the code to generate a random number between0(the base of the array) andarray.lengthwould be:

因此,給定以下包含25項的陣列,生成0(陣列的基)和陣列之間隨機數的程式碼。長度是:

String[] i = new String[25];
Random rand = new Random();
int index = 0;

index = rand.nextInt( i.length );

Sincei.lengthwill return25, thenextInt( i.length )will return a number between the range of0-24. The other option is going withMath.Randomwhich works in the same way.

因為我。長度將返回25。長度)將返回0-24之間的數值。另一個選擇是數學。用同樣的方法。

index = (int) Math.floor(Math.random() * i.length);

For a better understanding, check out forum postRandom Intervals (archive.org).

為了更好的理解,請檢視論壇釋出的隨機間隔(archive.org)。

#10


41

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:

請原諒我過於挑剔,但是大多數人提出的解決辦法是……分鐘+提高。nextInt(max - min + 1)似乎很危險,因為以下事實:

  • rng.nextInt(n)cannot reachInteger.MAX_VALUE.
  • rng.nextInt(n)不能達到Integer.MAX_VALUE。
  • (max - min)may cause overflow whenminis negative.
  • (最大值-最小值)當最小值為負值時可能會導致溢位。

A foolproof solution would return correct results for anymin <= maxwithin [Integer.MIN_VALUE,Integer.MAX_VALUE]. Consider the following naive implementation:

一個簡單的解決方案將返回在[Integer]內的任何min <= max的正確結果。MIN_VALUE,Integer.MAX_VALUE]。考慮以下簡單實現:

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 thewhileloop will always be 50% or higher.

儘管效率不高,但請注意while迴圈中成功的概率總是50%或更高。

#11


23

I wonder if any of the random number generating methods provided by anApache Commons Mathlibrary would fit the bill.

我想知道Apache Commons Math庫提供的任何隨機數生成方法是否適用。

For example:RandomDataGenerator.nextIntorRandomDataGenerator.nextLong

例如:RandomDataGenerator。nextInt或RandomDataGenerator.nextLong

#12


20

 rand.nextInt((max+1) - min) + min;

#13


20

Let us take an example.

讓我們舉個例子。

Suppose I wish to generate a number between5-10:

假設我想生成一個介於5-10之間的數:

int max = 10;
int min = 5;
int diff = max - min;
Random rn = new Random();
int i = rn.nextInt(diff + 1);
i += min;
System.out.print("The Random Number is " + i);

Let us understand this...

讓我們明白這一點……

Initialize max with highest value and min with the lowest value.

用最大值初始化max,用最小值初始化min。

Now, we need to determine how many possible values can be obtained. For this example, it would be:

現在,我們需要確定可以得到多少可能的值。對於這個例子,它將是:

5, 6, 7, 8, 9, 10

5 6 7 8 9 10

So, count of this would be max - min + 1.

所以這個的計數就是最大值-最小值+ 1。

i.e. 10 - 5 + 1 = 6

即10 - 5 + 1 = 6

The random number will generate a number between0-5.

隨機數將在0-5之間生成一個數字。

i.e. 0, 1, 2, 3, 4, 5

即0 1 2 3 4 5。

Adding theminvalue to the random number would produce:

將最小值加到隨機數中會產生:

5, 6, 7, 8, 9, 10

5 6 7 8 9 10

Hence we obtain the desired range.

因此我們得到了期望的範圍。

#14


17

Generate a random number for the difference of min and max by using thenextint(n)method and then add min number to the result:

使用nextint(n)方法生成最小和最大差的隨機數,然後在結果中新增最小值:

Random rn = new Random();
int result = rn.nextInt(max - min + 1) + min;
System.out.println(result);

#15


16

Here's a helpful class to generate randomintsin a range with any combination of inclusive/exclusive bounds:

這裡有一個很有用的類,可以在包含/獨佔邊界的任意組合中生成任意範圍內的隨機輸入:

import java.util.Random;

public class RandomRange extends Random {
    public int nextIncInc(int min, int max) {
        return nextInt(max - min + 1) + min;
    }

    public int nextExcInc(int min, int max) {
        return nextInt(max - min) + 1 + min;
    }

    public int nextExcExc(int min, int max) {
        return nextInt(max - min - 1) + 1 + min;
    }

    public int nextIncExc(int min, int max) {
        return nextInt(max - min) + min;
    }
}

#16


15

In case of rolling a dice it would be random number between 1 to 6 (not 0 to 6), so:

擲骰子時,隨機數為1到6(不是0到6),因此:

face = 1 + randomNumbers.nextInt(6);

#17


15

This methods might be convenient to use:

這些方法可能便於使用:

This method will return a random numberbetweenthe provided min and max value:

該方法將在提供的最小值和最大值之間返回一個隨機數:

public static int getRandomNumberBetween(int min, int max) {
    Random foo = new Random();
    int randomNumber = foo.nextInt(max - min) + min;
    if (randomNumber == min) {
        // Since the random number is between the min and max values, simply add 1
        return min + 1;
    } else {
        return randomNumber;
    }
}

and this method will return a random numberfromthe provided min and max value (so the generated number could also be the min or max number):

該方法將從所提供的最小值和最大值中返回一個隨機數(因此生成的數也可以是最小值或最大值):

public static int getRandomNumberFrom(int min, int max) {
    Random foo = new Random();
    int randomNumber = foo.nextInt((max + 1) - min) + min;

    return randomNumber;
}

#18


14

int random = minimum + Double.valueOf(Math.random()*(maximum-minimun)).intValue();

Or take a look to RandomUtils fromApache Commons.

或者看看Apache Commons中的RandomUtils。

#19


13

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 theMersenne twisterinstead. There isa Java implementation.

當您需要很多隨機數時,我不推薦API中的隨機類。它的週期太短了。試試Mersenne twister。有一個Java實現。

#20


13

public static Random RANDOM = new Random(System.nanoTime());

public static final float random(final float pMin, final float pMax) {
    return pMin + RANDOM.nextFloat() * (pMax - pMin);
}

#21


13

Here is a simple sample that shows how to generate random number from closed[min, max]range, whilemin <= max is true

這裡有一個簡單的示例,展示瞭如何從封閉的[min, max]範圍中生成隨機數,而min <= max為真

You can reuse it as field in hole class, also having allRandom.classmethods in one place

您可以將它作為一個欄位在洞類中重用,也可以任意使用。類方法在一個地方

Results example:

結果示例:

RandomUtils random = new RandomUtils();
random.nextInt(0, 0); // returns 0
random.nextInt(10, 10); // returns 10
random.nextInt(-10, 10); // returns numbers from -10 to 10 (-10, -9....9, 10)
random.nextInt(10, -10); // throws assert

Sources:

來源:

import junit.framework.Assert;
import java.util.Random;

public class RandomUtils extends Random {

    /**
     * @param min generated value. Can't be > then max
     * @param max generated value
     * @return values in closed range [min, max].
     */
    public int nextInt(int min, int max) {
        Assert.assertFalse("min can't be > then max; values:[" + min + ", " + max + "]", min > max);
        if (min == max) {
            return max;
        }

        return nextInt(max - min + 1) + min;
    }
}

#22


13

Just use theRandomclass:

使用隨機類:

Random ran = new Random();
// Assumes max and min are non-negative.
int randomInt = min + ran.nextInt(max - min + 1);

#23


13

I found this exampleGenerate random numbers:

我發現這個例子產生隨機數:


This example generates random integers in a specific range.

此示例生成特定範圍內的隨機整數。

import java.util.Random;

/** Generate random integers in a certain range. */
public final class RandomRange {

  public static final void main(String... aArgs){
    log("Generating random integers in the range 1..10.");

    int START = 1;
    int END = 10;
    Random random = new Random();
    for (int idx = 1; idx <= 10; ++idx){
      showRandomInteger(START, END, random);
    }

    log("Done.");
  }

  private static void showRandomInteger(int aStart, int aEnd, Random aRandom){
    if ( aStart > aEnd ) {
      throw new IllegalArgumentException("Start cannot exceed End.");
    }
    //get the range, casting to long to avoid overflow problems
    long range = (long)aEnd - (long)aStart + 1;
    // compute a fraction of the range, 0 <= frac < range
    long fraction = (long)(range * aRandom.nextDouble());
    int randomNumber =  (int)(fraction + aStart);    
    log("Generated : " + randomNumber);
  }

  private static void log(String aMessage){
    System.out.println(aMessage);
  }
} 

An example run of this class :

這個類的一個執行示例:

Generating random integers in the range 1..10.
Generated : 9
Generated : 3
Generated : 3
Generated : 9
Generated : 4
Generated : 1
Generated : 3
Generated : 9
Generated : 10
Generated : 10
Done.

#24


13

You can achieve that concisely in Java 8:

您可以在Java 8中簡潔地實現這一點:

Random random = new Random();

int max = 10;
int min = 5;
int totalNumber = 10;

IntStream stream = random.ints(totalNumber, min, max);
stream.forEach(System.out::println);

#25


11

Another option is just usingApache Commons:

另一個選擇是使用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);
    // ...
 }

#26


10

If you want to try the answer with the most votes above, you can simply use this code:

如果你想嘗試上面投票最多的答案,你可以使用以下程式碼:

public class Randomizer
{
    public static int generate(int min,int max)
    {
        return min + (int)(Math.random() * ((max - min) + 1));
    }

    public static void main(String[] args)
    {
        System.out.println(Randomizer.generate(0,10));
    }
}

It is just clean and simple.

它就是乾淨和簡單。

#27


10

private static Random random = new Random();    

public static int getRandomInt(int min, int max){
  return random.nextInt(max - min + 1) + min;
}

OR

public static int getRandomInt(Random random, int min, int max)
{
  return random.nextInt(max - min + 1) + min;
}

#28


10

It's better to useSecureRandomrather than just Random.

最好使用SecureRandom,而不是隨機使用。

public static int generateRandomInteger(int min, int max) {
    SecureRandom rand = new SecureRandom();
    rand.setSeed(new Date().getTime());
    int randomNum = rand.nextInt((max - min) + 1) + min;
    return randomNum;
}

#29


8

rand.nextInt((max+1) - min) + min;

This is working fine.

這是工作正常。

#30


7

import java.util.Random; 

public class RandomUtil {
    // Declare as class variable so that it is not re-seeded every call
    private static Random random = new Random();

    /**
     * Returns a psuedo-random number between min and max (both inclusive)
     * @param min Minimim value
     * @param max Maximim value. Must be greater than min.
     * @return Integer between min and max (both inclusive)
     * @see java.util.Random#nextInt(int)
     */
    public static int nextInt(int min, int max) {
        // nextInt is normally exclusive of the top value,
        // so add 1 to make it inclusive
        return random.nextInt((max - min) + 1) + min;
    }
}