如何在特定范围内生成随机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`.
下面是一个简单的示例,它显示了如何从闭合的[min,max]范围生成随机数,而min<=max为真
您可以将其作为孔中字段类重用,也可以将所有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;
}
}
这里有一个有用的类,可以在包含/排除边界的任意组合范围内生成随机整数:
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;
}
}
使用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)
}
这将生成范围(最小值-最大值)不重复的随机数列表。
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);
}
}
希望这对你有所帮助。