我使用以下代码生成随机整数:
public static int randInt(int min, int max) {
// NOTE: Usually this should be a field rather than a method
// variable so that it is not re-seeded every call.
Random rand = new Random();
// 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;
}
我这样使用它:
int count = randInt(1, 4);
System.out.println(count);
但它会间歇性地显示相同的数字两次,有时甚至连续显示 3 次。有没有办法检查最后生成的数字是否是新生成的数字并将其更改为下一个随机数字等等?
谢谢。
最佳答案
当然。你的范围很窄。如果我计算得当,有 25% 的机会(四分之一的机会)你会连续出现两个相同的数字,大约 6% 的机会(十六分之一的机会)你会连续出现三个相同的数字。连续的相同数字。这与抛硬币并连续两次或三次出现“正面”没有显着不同。But it intermittently displays the same number twice, and sometime even 3 times in a row.
Is there any way to do a check if the last generated number is the new generated one and change it to next next random and so on?
保留最后一个值并检查。下面是一些粗略的 Java:
class NonRepeatRandom {
Random r=new Random();
int lastValue=-1;
int randInt(int min, int max) {
int result;
do {
result = rand.nextInt((max - min) + 1) + min;
} while (result==lastValue);
lastValue=result;
return(result);
}
}
关于java - 某个范围内的随机数生成器有时会输出相同的数字两次,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31004048/