0

在我的 Android 应用程序中,我需要从指定范围内选择两个随机整数。下面的代码有效,但它并不是真正选择一个随机整数,而是对整数进行洗牌。randomNum2= (int)it.next();让我烦恼的是,由于代码中的位,我必须将最大 int 指定为实际上比最大值小一。如果我将正确的数字(当前为 127)作为最大值,那么我会收到错误java.util.NoSuchElementException,因为它正在寻找 128 作为下一次迭代。在我使用之前rand = new Random(); randomNum1 = rand.nextInt(max - min + 1) + min; randomNum2 = rand.nextInt(max - min + 1) + min;但问题是两个随机整数最终可能相同,我需要它们是唯一的。那么任何人都可以提出一种更好的方法来从最小/最大整数范围中获取两个随机数吗?这是我的代码:

    int min = 1;
int max = 126;
int randomNum1;
int randomNum2;
List<Integer> choicesL;

public void randomTwo() {
    choicesL = new LinkedList<Integer>();
    for (int i = min; i <= max; i++) {
        choicesL.add(i);
    }
    Collections.shuffle(choicesL);
    Iterator<Integer> it = choicesL.iterator();
    while (it.hasNext())
    {
        randomNum1= (int)it.next();
        randomNum2= (int)it.next();

    }

}
4

2 回答 2

1

您可以使用旧代码,但使用循环 while。

rand = new Random(); 
randomNum1 = rand.nextInt(max - min + 1) + min;
randomNum2 = rand.nextInt(max - min + 1) + min;

while (randomNum2==randomNum1){
    randomNum2 = rand.nextInt(max - min + 1) + min;
}

编辑

有很多方法可以寻找随机数。我不知道你是否知道这一点,但在此之下有很多统计研究。如果您需要一种快速计算随机数的方法,这很棒。但是您必须知道,经过大量时间后,用户可以知道您的随机数的分布情况。如果你想改进你的代码,也许你可以检查:

http://en.wikipedia.org/wiki/Box%E2%80%93Muller_transform

http://en.wikipedia.org/wiki/Ziggurat_algorithm

当然,我认为网上还有更多的理论

于 2012-12-12T16:24:17.063 回答
0

您可以使用 aSet并继续插入元素,直到集合的大小为 2。
对于少量元素(与范围的大小相比),这应该比填充 + 洗牌更有效。

int max = 126;
int min = 1;
int size = 2;
Set<Integer> set = new HashSet<Integer>();
Random r = new Random();
while (set.size() != size) {
    set.add(r.nextInt(max - min + 1) + min);
}
System.out.println(set);

注意:这是一个通用答案,适用于所有需要的尺寸(当然假设size <= max - min

于 2012-12-12T16:21:03.877 回答