随机方法的java问题
我有一个方法不能正常工作。 该方法假定对1到20之间的一组数字进行随机排序(每个数字 必须只出现一次)。 我的问题是,当我运行程序时,一些数字会重复几次。 代码如下:
public static int randomize(int index) {
//This array will hold the 20 numbers.
int[] randomIndex = new int[20];
Random ranNum = new Random();
for (int x = 0; x<20; x++) {
int temp;
//The number is generated randomly and saved in temp.
temp = ranNum.nextInt(20);
//This loop skips the first index.
if (x != 0){
/*Here, the loop is supposed to compare a generated number with
the previous one*/
for (int y = 1; y<=x; y++) {
while(temp == randomIndex[x-y] ) {
/*If the while loop finds that temp variable matches any previous
number it will generate another random number for it until it finds
no matches.*/
temp = ranNum.nextInt(20);
}
}
}
/*Once no match has been found for temp, the number is assigned to an index,
and the loop is executed with a x variable increment.
randomIndex[x] = temp;
}
//Finally the array with the set of random numbers is sent to the main function.
return randomIndex[index];
}
我得到了以下结果:
19, 19, 5, 16, 6, 2, 18, 1, 15, 1, 5, 19, 11, 4, 18, 0, 5, 18, 10.
所以现在我不知道该怎么办C
# 1 楼答案
使用
Random.nextInt()
时,无法保证生成的数字是唯一的。 你应该先生成从1到20的数字,然后将数字洗牌。现在问题变成了“如何随机洗牌?”也许你可以参考JDK的实现
洗牌数字的算法很简单:
# 2 楼答案
您可以使用以下方法来避免:
# 3 楼答案
我将生成数组的函数从1编辑为20:
希望这会有帮助
# 4 楼答案
看起来你试图通过拒绝生成你的随机数——也就是说,将每个随机数与之前接受的所有数字进行比较,然后重新生成新的随机数,直到找到一个与所有随机数不同的随机数
正如其他人所提到的,生成从1到20的数字,并用随机排列将其洗牌,效率会高得多。然而,如果实施正确,你的方法应该是有效的。。。最终
随机洗牌实现可能如下所示:
以下是您发布的代码生成重复代码的两个原因。首先,当您拒绝一个候选随机数并重新生成一个新的随机数时,您需要将其与所有现有数进行比较,从一开始就重新启动内部(
y
)循环。你现有的代码不能做到这一点其次,我认为
new Random()
构造函数每次调用时都会生成不同的种子。如果是这样,那么randomize()
函数每次都会生成一个完全不同的随机列表,并从中返回所选索引。无论如何,返回整个数组更有意义