gpt4 book ai didi

java - 为什么我随机选择的数字的输出包含重复项?

转载 作者:太空宇宙 更新时间:2023-11-04 07:44:21 25 4
gpt4 key购买 nike

我的代码需要从 145 的列表中随机选择 6 个数字。

有一次,当我运行代码(如下)时,输出为 [4, 4, 17, 18, 27, 37]我没想到输出中有任何重复。怎么可能有重复项?我的代码应该在选择数字时从列表中删除它们。

    Random rng = new Random(); 
int size = 45;
int sixList[] = new int[6];
ArrayList<Integer> list = new ArrayList<Integer>(size);
ArrayList<Integer> list2 = new ArrayList<Integer>(6);
for(int i = 1; i <= size; i++) {
list.add(i);
}
Random rand = new Random();
for(int i = 0; list.size() > 39; i++){
int index = rand.nextInt(list.size());
if (index == 0){
index = rand.nextInt(list.size());
list2.add(index);
list.remove(index);
}else{
list2.add(index);
list.remove(index);
}
}
Collections.sort(list2);
System.out.print(list2);

最佳答案

问题在于您正在将索引值添加到随机数列表中。

更改您的代码

list2.add(index);
list.remove(index);

list2.add(list.remove(index));

关于java - 为什么我随机选择的数字的输出包含重复项?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15554712/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com