# random區間 - random java within range

## 從Java 8開始

``````int n = new SplittableRandom().nextInt(0, 1_001);
``````

``````int[] a = new SplittableRandom().ints(100, 0, 1_001).parallel().toArray();
``````

``````IntStream stream = new SplittableRandom().ints(100, 0, 1_001);
``````

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

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

x，y - 間隔例如（1,10）

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

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

``````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);
// ...
}
``````

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

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

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

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

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

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

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

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

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

• `rng.nextInt(n)`無法達到`Integer.MAX_VALUE`
• `min`為負時， `(max - min)`可能導致溢出。

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

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

5,6,7,8,9,10

min值添加到隨機數將產生：

5,6,7,8,9,10

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

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

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

return randomNumber;
}
``````

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

``````private static Random random = new Random();

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

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

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