[英]How do I generate random integers within a specific range in Java?
如何生成特定范围内的随机int
值?
以下方法存在与 integer 溢出相关的错误:
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`.
在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);
请参阅相关的 JavaDoc 。 这种方法的优点是不需要显式初始化java.util.Random实例,如果使用不当,可能会造成混乱和错误。
但是,相反,没有办法明确设置种子,因此在测试或保存游戏状态或类似情况等有用的情况下,可能难以重现结果。 在这些情况下,可以使用下面所示的 Java 1.7 之前的技术。
在 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;
}
请参阅相关的 JavaDoc 。 在实践中, java.util.Random类通常比java.lang.Math.random()更可取。
特别是,当标准库中有一个简单的 API 来完成任务时,不需要重新发明随机整数生成轮。
请注意,这种方法比nextInt
方法更有偏见,效率更低, https ://stackoverflow.com/a/738651/360211
实现此目的的一种标准模式是:
Min + (int)(Math.random() * ((Max - Min) + 1))
Java数学库函数 Math.random() 在[0,1)
范围内生成一个双精度值。 请注意,此范围不包括 1。
为了首先获得特定范围的值,您需要乘以要覆盖的值范围的大小。
Math.random() * ( Max - Min )
这将返回[0,Max-Min)
范围内的值,其中不包括 'Max-Min'。
例如,如果你想要[5,10)
,你需要覆盖五个整数值,所以你使用
Math.random() * 5
这将返回[0,5)
范围内的值,其中不包括 5。
现在您需要将此范围向上移动到您的目标范围。 您可以通过添加 Min 值来做到这一点。
Min + (Math.random() * (Max - Min))
您现在将获得[Min,Max)
范围内的值。 按照我们的示例,这意味着[5,10)
:
5 + (Math.random() * (10 - 5))
但是,这仍然不包括Max
并且您获得了双倍值。 为了获得包含的Max
,您需要将 1 添加到您的范围参数(Max - Min)
,然后通过强制转换为 int 来截断小数部分。 这是通过以下方式完成的:
Min + (int)(Math.random() * ((Max - Min) + 1))
你有它。 [Min,Max]
范围内的随机整数值,或根据示例[5,10]
:
5 + (int)(Math.random() * ((10 - 5) + 1))
利用:
Random ran = new Random();
int x = ran.nextInt(6) + 5;
整数x
现在是可能结果为5-10
的随机数。
利用:
minValue + rn.nextInt(maxValue - minValue + 1)
在java-8中,他们在Random
类中引入了ints(int randomNumberOrigin, int randomNumberBound)
方法。
例如,如果您想在 [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();
}
}
您也可以对double
和long
值执行此操作。 我希望它有帮助! :)
您可以将第二个代码示例编辑为:
Random rn = new Random();
int range = maximum - minimum + 1;
int randomNum = rn.nextInt(range) + minimum;
只需对您的第一个解决方案进行小修改就足够了。
Random rand = new Random();
randomNum = minimum + rand.nextInt((maximum - minimum) + 1);
在这里查看更多关于Random
的实现
ThreadLocalRandom
等价于类java.util.Random
用于多线程环境。 在每个线程中本地执行随机数的生成。 因此,通过减少冲突,我们可以获得更好的性能。
int rand = ThreadLocalRandom.current().nextInt(x,y);
x
, y
- 间隔,例如 (1,10)
Java中的Math.Random
类是从 0 开始的。 所以,如果你写这样的东西:
Random rand = new Random();
int x = rand.nextInt(10);
x
将介于0-9
之间。
因此,给定以下25
个项目的数组,生成0
(数组的基数)和array.length
之间的随机数的代码将是:
String[] i = new String[25];
Random rand = new Random();
int index = 0;
index = rand.nextInt( i.length );
由于i.length
将返回25
, nextInt( i.length )
将返回一个介于0-24
范围内的数字。 另一种选择是与Math.Random
一起使用,它的工作方式相同。
index = (int) Math.floor(Math.random() * i.length);
为了更好地理解,请查看论坛帖子Random Intervals (archive.org) 。
只需执行以下语句即可完成:
Randomizer.generate(0, 10); // Minimum of zero and maximum of ten
下面是它的源代码。
public class Randomizer {
public static int generate(int min, int max) {
return min + (int)(Math.random() * ((max - min) + 1));
}
}
它既干净又简单。
请原谅我的挑剔,但大多数人建议的解决方案,即min + rng.nextInt(max - min + 1))
似乎很危险,因为:
rng.nextInt(n)
无法达到Integer.MAX_VALUE
。(max - min)
min
为负数时可能会导致溢出。 一个万无一失的解决方案将为 [ Integer.MIN_VALUE
, Integer.MAX_VALUE
] 内的任何min <= max
返回正确的结果。 考虑以下简单的实现:
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.
我想知道Apache Commons Math库提供的任何随机数生成方法是否符合要求。
例如: RandomDataGenerator.nextInt
或RandomDataGenerator.nextLong
我用这个:
/**
* @param min - The minimum.
* @param max - The maximum.
* @return A random double between these numbers (inclusive the minimum and maximum).
*/
public static double getRandom(double min, double max) {
return (Math.random() * (max + 1 - min)) + min;
}
如果需要,您可以将其转换为整数。
让我们举个例子。
假设我希望生成一个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);
让我们明白这...
用最大值初始化最大值,用最小值初始化最小值。
现在,我们需要确定可以获得多少个可能的值。 对于此示例,它将是:
5、6、7、8、9、10
所以,这个计数将是 max - min + 1。
即 10 - 5 + 1 = 6
随机数将生成一个介于0-5之间的数字。
即 0、1、2、3、4、5
将最小值添加到随机数将产生:
5、6、7、8、9、10
因此,我们获得了所需的范围。
rand.nextInt((max+1) - min) + min;
从 Java 7 开始,您不应再使用
Random
。 对于大多数用途,现在选择的随机数生成器是ThreadLocalRandom
。
对于分叉连接池和并行流,请使用SplittableRandom
。
约书亚·布洛赫。 有效的Java。 第三版。
对于分叉连接池和并行流,使用SplittableRandom
通常更快,与Random
相比具有更好的统计独立性和均匀性属性。
要在[0, 1_000]:
范围内生成随机int
:
int n = new SplittableRandom().nextInt(0, 1_001);
要生成[0, 1_000]:
范围内的随机int[100]
值数组:
int[] a = new SplittableRandom().ints(100, 0, 1_001).parallel().toArray();
要返回随机值流:
IntStream stream = new SplittableRandom().ints(100, 0, 1_001);
使用nextint(n)方法为 min 和 max 的差生成一个随机数,然后将 min 数添加到结果中:
Random rn = new Random();
int result = rn.nextInt(max - min + 1) + min;
System.out.println(result);
只需使用Random类:
Random ran = new Random();
// Assumes max and min are non-negative.
int randomInt = min + ran.nextInt(max - min + 1);
这些方法使用起来可能很方便:
此方法将返回提供的最小值和最大值之间的随机数:
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;
}
要生成“在两个数字之间”的随机数,请使用以下代码:
Random r = new Random();
int lowerBound = 1;
int upperBound = 11;
int result = r.nextInt(upperBound-lowerBound) + lowerBound;
这会给你一个介于 1(包括)和 11(不包括)之间的随机数,所以通过加 1 来初始化 upperBound 值。例如,如果你想生成 1 到 10 之间的随机数,那么用 11 而不是初始化 upperBound 数10.
如果掷骰子,它将是 1 到 6(不是 0 到 6)之间的随机数,所以:
face = 1 + randomNumbers.nextInt(6);
int random = minimum + Double.valueOf(Math.random()*(maximum-minimum )).intValue();
或者看看Apache Commons的 RandomUtils 。
您可以在 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);
这是一个有用的类,可以在包含/排除边界的任意组合的范围内生成随机ints
:
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 Random RANDOM = new Random(System.nanoTime());
public static final float random(final float pMin, final float pMax) {
return pMin + RANDOM.nextFloat() * (pMax - pMin);
}
另一种选择是只使用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);
// ...
}
我发现这个例子生成随机数:
此示例生成特定范围内的随机整数。
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.
这是一个简单的示例,展示了如何从封闭的[min, max]
范围生成随机数,而min <= max is true
您可以将其作为孔类中的字段重用,同时将所有Random.class
方法放在一个地方
结果示例:
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
资料来源:
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;
}
}
最好使用SecureRandom而不是 Random。
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;
}
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;
}
Java 17 引入了RandomGenerator
接口,它提供了一个int nextInt(int origin, int bound)
方法来获取一个范围内的随机整数:
// Returns a random int between minimum (inclusive) & maximum (exclusive)
int randomInt = RandomGenerator.getDefault().nextInt(minimum, maximum);
除了用于 Java 17 中添加的新随机生成算法之外,该接口还添加到现有的随机生成类( Random
、 SecureRandom
、 SplittableRandom
和ThreadLocalRandom
)中。 因此,从 Java 17 开始,这些类具有这个有界的nextInt
方法:
new Random().nextInt(minimum, maximum);
new SecureRandom().nextInt(minimum, maximum);
new SplittableRandom().nextInt(minimum, maximum);
new ThreadLocalRandom().nextInt(minimum, maximum);
从 Java 17 开始,此方法是Random
和SecureRandom
的新方法。在 Java 17 之前, ThreadLocalRandom
和SplittableRandom
已经具有此方法,尽管它不是由共享接口指定的。
Random rng = new Random();
int min = 3;
int max = 11;
int upperBound = max - min + 1; // upper bound is exclusive, so +1
int num = min + rng.nextInt(upperBound);
System.out.println(num);
您可以使用此代码段来解决您的问题:
Random r = new Random();
int myRandomNumber = 0;
myRandomNumber = r.nextInt(maxValue - minValue + 1) + minValue;
使用 myRandomNumber (它会给你一个范围内的数字)。
我将简单说明问题提供的解决方案有什么问题以及为什么会出现错误。
解决方案1:
randomNum = minimum + (int)(Math.random()*maximum);
问题:randomNum 被分配的数值大于最大值。
解释:假设我们的最小值是 5,而你的最大值是 10。 Math.random()
中任何大于 0.6 的值都会使表达式的计算结果为 6 或更大,加上 5 会使它大于 10(你的最大值)。 问题是您将随机数乘以最大值(生成的数字几乎与最大值一样大),然后加上最小值。 除非最小值为 1,否则它是不正确的。 如其他答案所述,您必须切换到
randomNum = minimum + (int)(Math.random()*(maximum-minimum+1))
+1 是因为Math.random()
永远不会返回 1.0。
解决方案2:
Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt() % n;
randomNum = minimum + i;
您的问题是,如果第一项小于 0,则 '%' 可能会返回负数。由于rn.nextInt()
以约 50% 的机会返回负值,因此您也不会得到预期的结果。
然而,这几乎是完美的。 您只需进一步查看 Javadoc, nextInt(int n) 。 使用该方法可用,做
Random rn = new Random();
int n = maximum - minimum + 1;
int i = rn.nextInt(n);
randomNum = minimum + i;
也会返回想要的结果。
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;
}
}
使用 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)
}
我正在考虑通过使用以下方法将生成的随机数线性归一化到所需的范围内。 令x
为随机数,令a
和b
为所需归一化数的最小和最大范围。
然后下面只是一个非常简单的代码片段,用于测试线性映射产生的范围。
public static void main(String[] args) {
int a = 100;
int b = 1000;
int lowest = b;
int highest = a;
int count = 100000;
Random random = new Random();
for (int i = 0; i < count; i++) {
int nextNumber = (int) ((Math.abs(random.nextDouble()) * (b - a))) + a;
if (nextNumber < a || nextNumber > b) {
System.err.println("number not in range :" + nextNumber);
}
else {
System.out.println(nextNumber);
}
if (nextNumber < lowest) {
lowest = nextNumber;
}
if (nextNumber > highest) {
highest = nextNumber;
}
}
System.out.println("Produced " + count + " numbers from " + lowest
+ " to " + highest);
}
你可以这样做:
import java.awt.*;
import java.io.*;
import java.util.*;
import java.math.*;
public class Test {
public static void main(String[] args) {
int first, second;
Scanner myScanner = new Scanner(System.in);
System.out.println("Enter first integer: ");
int numOne;
numOne = myScanner.nextInt();
System.out.println("You have keyed in " + numOne);
System.out.println("Enter second integer: ");
int numTwo;
numTwo = myScanner.nextInt();
System.out.println("You have keyed in " + numTwo);
Random generator = new Random();
int num = (int)(Math.random()*numTwo);
System.out.println("Random number: " + ((num>numOne)?num:numOne+num));
}
}
Random random = new Random();
int max = 10;
int min = 3;
int randomNum = random.nextInt(max) % (max - min + 1) + min;
可以使用以下代码:
ThreadLocalRandom.current().nextInt(rangeStart, rangeEndExclusive)
您可以使用以下方式来做到这一点:
int range = 10;
int min = 5
Random r = new Random();
int = r.nextInt(range) + min;
int randomNum = 5 + (int)(Math.random()*5);
范围 5-10
我只是使用 Math.random() 生成一个随机数并将其乘以一个大数,比如 10000。所以,我得到一个介于 0 到 10,000 之间的数字并将这个数字称为i
。 现在,如果我需要 (x, y) 之间的数字,请执行以下操作:
i = x + (i % (y - x));
所以,所有i
都是 x 和 y 之间的数字。
要消除评论中指出的偏差,而不是将其乘以 10000(或大数),而是乘以 (yx)。
这是执行此操作的简单方法。
import java.util.Random;
class Example{
public static void main(String args[]){
/*-To test-
for(int i = 1 ;i<20 ; i++){
System.out.print(randomnumber()+",");
}
*/
int randomnumber = randomnumber();
}
public static int randomnumber(){
Random rand = new Random();
int randomNum = rand.nextInt(6) + 5;
return randomNum;
}
}
那里 5 是随机数的起点。 6 是包含数字 5 的范围。
假设您想要介于 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);
}
我的一个朋友今天在大学里问过我同样的问题(他的要求是生成一个介于 1 和 -1 之间的随机数)。 所以我写了这个,到目前为止它在我的测试中运行良好。 理想情况下,有很多方法可以在给定范围内生成随机数。 尝试这个:
功能:
private static float getRandomNumberBetween(float numberOne, float numberTwo) throws Exception{
if (numberOne == numberTwo){
throw new Exception("Both the numbers can not be equal");
}
float rand = (float) Math.random();
float highRange = Math.max(numberOne, numberTwo);
float lowRange = Math.min(numberOne, numberTwo);
float lowRand = (float) Math.floor(rand-1);
float highRand = (float) Math.ceil(rand+1);
float genRand = (highRange-lowRange)*((rand-lowRand)/(highRand-lowRand))+lowRange;
return genRand;
}
像这样执行:
System.out.println( getRandomNumberBetween(1,-1));
我认为这段代码会为它工作。 请试试这个:
import java.util.Random;
public final class RandomNumber {
public static final void main(String... aArgs) {
log("Generating 10 random integers in range 1..10.");
int START = 1;
int END = 10;
Random randomGenerator = new Random();
for (int idx=1; idx<=10; ++idx) {
// int randomInt=randomGenerator.nextInt(100);
// log("Generated : " + randomInt);
showRandomInteger(START,END,randomGenerator);
}
log("Done");
}
private static void log(String aMessage) {
System.out.println(aMessage);
}
private static void showRandomInteger(int aStart, int aEnd, Random aRandom) {
if (aStart > aEnd) {
throw new IllegalArgumentException("Start cannot exceed End.");
}
long range = (long)aEnd - (long)aStart + 1;
long fraction = (long) (range * aRandom.nextDouble());
int randomNumber = (int) (fraction + aStart);
log("Generated" + randomNumber);
}
}
这将生成范围 (Min - Max)且没有重复的随机数列表。
generateRandomListNoDuplicate(1000, 8000, 500);
添加此方法。
private void generateRandomListNoDuplicate(int min, int max, int totalNoRequired) {
Random rng = new Random();
Set<Integer> generatedList = new LinkedHashSet<>();
while (generatedList.size() < totalNoRequired) {
Integer radnomInt = rng.nextInt(max - min + 1) + min;
generatedList.add(radnomInt);
}
}
希望这会帮助你。
我创建了一种方法来获取给定范围内的唯一整数。
/*
* 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;
}
如果您已经使用Commons Lang API 3.x
或最新版本,那么有一类用于生成随机数RandomUtils
。
public static int nextInt(int startInclusive, int endExclusive)
返回指定范围内的随机整数。
参数:
startInclusive - 指定的起始值
endExclusive - 指定的结束值
int random = RandomUtils.nextInt(999,1000000);
注意:在RandomUtils中有很多随机数生成方法
下面的代码生成一个介于 100,000 和 900,000 之间的随机数。 此代码将生成六位数的值。 我正在使用此代码生成六位数的OTP 。
使用import java.util.Random
来使用这个随机方法。
import java.util.Random;
// Six digits random number generation for OTP
Random rnd = new Random();
long longregisterOTP = 100000 + rnd.nextInt(900000);
System.out.println(longregisterOTP);
下面是另一个使用 Random 和 forEach 的例子
int firstNum = 20;//Inclusive
int lastNum = 50;//Exclusive
int streamSize = 10;
Random num = new Random().ints(10, 20, 50).forEach(System.out::println);
将 java.util 用于 Random 用于一般用途。
您可以定义最小和最大范围以获得这些结果。
Random rand=new Random();
rand.nextInt((max+1) - min) + min;
int func(int max, int min){
int range = max - min + 1;
// Math.random() function will return a random no between [0.0,1.0).
int res = (int) ( Math.random()*range)+min;
return res;
}
使用 Apache Lang3 Commons
Integer.parseInt(RandomStringUtils.randomNumeric(6, 6));
最小值 100000 到最大值 999999
您可以使用 Random 类生成随机数,然后使用 .nextInt(maxNumber) 生成随机数。 maxNumber 是生成随机数时希望最大的数字。 但请记住,Random 类为您提供数字 0 到 maxNumber-1。
Random r = new Random();
int i = r.nextInt();
另一种方法是使用 Math.Random() 类,学校中的许多课程都要求您使用它,因为它更有效并且您不必声明新的 Random 对象。 要使用 Math.Random() 获取随机数,请输入:
Math.random() * (max - min) + min;
[min..max] 范围内的随机数:
int randomFromMinToMaxInclusive = ThreadLocalRandom.current()
.nextInt(min, max + 1);
以前的大多数建议都没有考虑“溢出”。 例如:min = Integer.MIN_VALUE, max = 100。到目前为止,我采用的正确方法之一是:
final long mod = max- min + 1L;
final int next = (int) (Math.abs(rand.nextLong() % mod) + min);
https://sourceforge.net/projects/stochunit/有一个库,用于处理范围的选择。
StochIntegerSelector randomIntegerSelector = new StochIntegerSelector();
randomIntegerSelector.setMin(-1);
randomIntegerSelector.setMax(1);
Integer selectInteger = randomIntegerSelector.selectInteger();
它具有边缘包含/排除。
import java.util.Random;
public class RandomSSNTest {
public static void main(String args[]) {
generateDummySSNNumber();
}
//831-33-6049
public static void generateDummySSNNumber() {
Random random = new Random();
int id1 = random.nextInt(1000);//3
int id2 = random.nextInt(100);//2
int id3 = random.nextInt(10000);//4
System.out.print((id1+"-"+id2+"-"+id3));
}
}
你也可以使用
import java.util.concurrent.ThreadLocalRandom;
Random random = ThreadLocalRandom.current();
但是,此类在多线程环境中表现不佳。
为了避免重复多次说过的话,我将通过使用SecureRandom类为那些需要加密更强的伪随机数生成器的人展示一个替代方案,该类扩展了类Random
。 从源代码可以阅读:
此类提供了一个加密的强随机数生成器 (RNG)。 加密强随机数至少符合 FIPS 140-2,加密模块的安全要求,第 4.9.1 节中指定的统计随机数生成器测试。 此外,SecureRandom 必须产生非确定性的输出。 因此,传递给 SecureRandom 对象的任何种子材料都必须是不可预测的,并且所有 SecureRandom 输出序列必须具有加密强度,如 RFC 1750:安全随机性建议中所述。
调用者通过无参数构造函数或 getInstance 方法之一获取 SecureRandom 实例:
SecureRandom random = new SecureRandom();
许多 SecureRandom 实现采用伪随机数生成器 (PRNG) 的形式,这意味着它们使用确定性算法从真正的随机种子生成伪随机序列。 其他实现可能会产生真正的随机数,而其他实现可能会使用这两种技术的组合。
要生成介于min
和max
之间的随机数:
public static int generate(SecureRandom secureRandom, int min, int max) {
return min + secureRandom.nextInt((max - min) + 1);
}
对于给定的min
(包括)和max
(不包括)值:
return min + secureRandom.nextInt((max - min));
运行代码示例:
public class Main {
public static int generate(SecureRandom secureRandom, int min, int max) {
return min + secureRandom.nextInt((max - min) + 1);
}
public static void main(String[] arg) {
SecureRandom random = new SecureRandom();
System.out.println(generate(random, 0, 2 ));
}
}
诸如stackoverflow 、 baeldung 、 geeksforgeeks 之类的源提供了Random
和SecureRandom
类之间的比较。
从baeldung可以读到:
使用 SecureRandom 的最常见方式是生成 int、long、float、double 或 boolean 值:
int randomInt = secureRandom.nextInt();
long randomLong = secureRandom.nextLong();
浮动 randomFloat = secureRandom.nextFloat();
双 randomDouble = secureRandom.nextDouble();
boolean randomBoolean = secureRandom.nextBoolean();为了生成 int 值,我们可以传递一个上限作为参数:
int randomInt = secureRandom.nextInt(upperBound);
此外,我们可以为 int、double 和 long 生成一个值流:
IntStream randomIntStream = secureRandom.ints();
LongStream randomLongStream = secureRandom.longs();
DoubleStream randomDoubleStream = secureRandom.doubles();对于所有流,我们可以显式设置流大小:
IntStream intStream = secureRandom.ints(streamSize);
此类提供了超出此问题范围的其他几个选项(例如,选择基础随机数生成器)。
尝试使用org.apache.commons.lang.RandomStringUtils
类。 是的,它有时会给出相邻的重复数字,但它会给出 5 到 15 之间的值:
while (true)
{
int abc = Integer.valueOf(RandomStringUtils.randomNumeric(1));
int cd = Integer.valueOf(RandomStringUtils.randomNumeric(2));
if ((cd-abc) >= 5 && (cd-abc) <= 15)
{
System.out.println(cd-abc);
break;
}
}
使用 Java 8 流,
public static List<Integer> generateNumbers(int initialCapacity, int randomBound, Boolean sorted, Random random) {
List<Integer> numbers = random.ints(initialCapacity, 1, randomBound).boxed().collect(Collectors.toList());
if (sorted)
numbers.sort(null);
return numbers;
}
在此示例中,它从 1-Randombound 生成数字。
一种在 a 和 b 之间生成 n 个随机数的简单方法,例如 a =90, b=100, n =20
Random r = new Random();
for(int i =0; i<20; i++){
System.out.println(r.ints(90, 100).iterator().nextInt());
}
r.ints()
返回一个IntStream
并有几个有用的方法,看看它的API 。
public static void main(String[] args) {
Random ran = new Random();
int min, max;
Scanner sc = new Scanner(System.in);
System.out.println("Enter min range:");
min = sc.nextInt();
System.out.println("Enter max range:");
max = sc.nextInt();
int num = ran.nextInt(min);
int num1 = ran.nextInt(max);
System.out.println("Random Number between given range is " + num1);
}
根据 user42155 的要求,这是一个函数,它在lowerBoundIncluded
和upperBoundIncluded
定义的范围内准确返回一个整数随机数
SplittableRandom splittableRandom = new SplittableRandom();
BiFunction<Integer,Integer,Integer> randomInt = (lowerBoundIncluded, upperBoundIncluded)
-> splittableRandom.nextInt(lowerBoundIncluded, upperBoundIncluded + 1);
randomInt.apply( …, … ); // gets the random number
…或更短的随机数的一次性生成
new SplittableRandom().nextInt(lowerBoundIncluded, upperBoundIncluded + 1);
java中生成特定范围内的随机整数的方法有很多种,我们将探讨生成范围内随机数的不同方法。
让我们使用 Math.random 方法生成给定范围 [min, max 内的随机数。要使用 Math.random() 生成范围内的随机数,请按照以下步骤操作:
声明范围的最小值
声明范围的最大值
使用公式 Math.floor(Math.random()*(max-min+1)+min) 生成包含最小值和最大值的值。
public class MathRandomExample { public static void main(String args[]) { int min = 1; int max = 10; System.out.println("random value in int from "+min+" to "+max+ ":"); int random_int = (int)Math.floor(Math.random()*(max-min+1)+min); System.out.println(random_int); } }
注意:只有在需要整数或浮点随机值时才能使用此方法。
我们也可以使用 java.util.Random 的实例来做同样的事情。
让我们使用 java.util.Random.nextInt 方法来获取一个随机数。
public class RandomNextIntExample {
public static void main(String args[]) {
int min = 1;
int max = 10;
Random random = new Random();
System.out.println(random.nextInt(max - min) + min);
}
}
java.util.Random.ints 方法返回一个随机整数的 IntStream。 因此,我们可以利用 java.util.Random.ints 方法并返回一个随机数:
public class RandomIntsExample {
public static void main(String args[]) {
int min = 1;
int max = 10;
Random random = new Random();
System.out.println(random.ints(min, max)
.findFirst()
.getAsInt());
}
}
java中有很多方法可以生成随机数。 但我只会展示两种方式。
如果我们想在指定范围内生成随机数,我们可以使用以下公式。
Math.random() * (max - min + 1) + min
整数生成:
int b = (int)(Math.random()*(max-min+1)+min);
System.out.println(b);
双代:
double a = Math.random()*(max-min+1)+min;
System.out.println(a);
另一种生成随机数的方法是使用java.util包的 Java Random 类。
首先,导入类java.util.Random 。
import java.util.Random;
创建 Random 类的对象。
Random random = new Random();
调用以下任何方法:
随机整数生成:
// Generates random integers 0 to 49
int x = random.nextInt(50);
// Generates random integers 100 to 1000
int y = random.nextInt(100, ,1001);
// Prints random integer values
随机双生成:
// Generates Random doubles values
double a = random.nextDouble();
// Generates Random doubles values 100 to 1000
double b = random.nextDouble(100, 1001);
我们可以使用随机 class 通过传递原点和绑定值来生成指定范围之间的值。 请注意,绑定值是独占的。
新的 Random().nextInt(1, 10)
如果您不想重新发明轮子,她是一个单行的、不费吹灰之力的解决方案:
RandomStringUtils.randomNumeric(count); // where count is the number of digits you want in the random number.
Apache Utils 提供了许多选项来生成您想要的任何格式的随机数。
因为Android 问题重定向到这里,这就是您使用 Kotlin 的方式:
val r = (0..10).random() // A random integer between 0 and 10 inclusive
这适用于 Kotlin 1.3及更高版本。 参考这个答案。
如果我们有对安全敏感的应用程序,我们应该使用 SecureRandom。
import java.security.SecureRandom;
public class Main {
public static void main(String... args){
int max=13;
int min =1;
int randomWithSecureRandom = new SecureRandom().nextInt(max - min) + min;
System.out.println(randomWithSecureRandom);
}
}
以下代码段将给出 0 到 10000 之间的随机值:
import java.util.Random;
public class Main
{
public static void main(String[] args) {
Random rand = new Random();
System.out.printf("%04d%n", rand.nextInt(10000));
}
}
您可以执行以下操作。
import java.util.Random;
public class RandomTestClass {
public static void main(String[] args) {
Random r = new Random();
int max, min;
Scanner scanner = new Scanner(System.in);
System.out.println("Enter maximum value : ");
max = scanner.nextInt();
System.out.println("Enter minimum value : ");
min = scanner.nextInt();
int randomNum;
randomNum = r.nextInt(max) + min;
System.out.println("Random Number : " + randomNum);
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.