java - 某个范围内的随机数生成器有时会输出相同的数字两次

标签 java android

我使用以下代码生成随机整数:

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 次。有没有办法检查最后生成的数字是否是新生成的数字并将其更改为下一个随机数字等等?

谢谢。

最佳答案

But it intermittently displays the same number twice, and sometime even 3 times in a row.

当然。你的范围很窄。如果我计算得当,有 25% 的机会(四分之一的机会)你会连续出现两个相同的数字,大约 6% 的机会(十六分之一的机会)你会连续出现三个相同的数字。连续的相同数字。这与抛硬币并连续两次或三次出现“正面”没有显着不同。

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/

相关文章:

java - 导入org.hibernate.validator.Length无法解析?

java - 在另一个项目 Eclipse 中调用一个类

java - 以编程方式登录网站

java - AutoCompleteTextView onItemSelectedListener 不起作用

android - 在 Android 中共享图像和文本

Android - 发布到 RESTful Web 服务

java - Mockito doReturn().when() 调用原始方法

java - 如何将对象转换为它不继承的类型?

Android Studio : ButterKnife 6. 1.0 重复类:$$View Injector

android - 无法跨过 Eclipse 中的断点