Java Random seed偽隨機
阿新 • • 發佈:2018-12-25
在指定區間內獲得隨機數,隨機的幾種方式。
方法:
/** * 在指定區間[min,max)通過種子seed設定偽隨機數 * @param min 最小值 * @param max 最大值 * @param seed 種子 */ public static int random(int min, int max, long seed) { Random random = new Random(seed); final int size = 100; for (int i = 0; i < size ; i++) { int randomNum = random.nextInt(max); if (randomNum > min && randomNum < max) { return randomNum; } } // 確保生成隨機數。 return random(min, max, send + size); }
測試:
public static void main(String[] args) {
for (int j = 0; j < 3; j++) {
System.out.println(String.format("第%d遍", j));
for (int i = 0; i < 10; i++) {
System.out.print(random(0,100, i) + " ");
}
System.out.println();
}
}
結果:
Apache.commons.lang3包中也有RandomUtils生成隨機數, 一般的需求足夠了。但是沒法加seed,無法生成可控的隨機數!
<-- org.apache.commons.lang3 -->
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.8.1</version>
</dependency>
方法:
public static int random(int min, int max) { return RandomUtils.nextInt(min, max); }
測試:
public static void main(String[] args) {
for (int j = 0; j < 3; j++) {
System.out.println(String.format("第%d遍", j));
for (int i = 0; i < 10; i++) {
System.out.print(RandomUtils.nextInt(0,100) + " ");
}
System.out.println();
}
}