【发布时间】:2013-03-21 17:53:48
【问题描述】:
我的代码需要从1到45的列表中随机选择6个数字。
当我运行我的代码(如下)时,输出为[4, 4, 17, 18, 27, 37]。 我没想到输出中有任何重复。怎么可能有重复?我的代码应该从list 中删除被选中的数字。
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);
【问题讨论】:
-
要进行彩票选择,最简单的方法是从 1 到 45 的数字列表中随机抽取前 6 个。
-
你想要 1-45 的 6 位数字,这就是你得到的,不是吗?
-
我不明白这里问了什么,你应该澄清一下
-
但我想知道为什么控制台打印 4, 4, 17, 18, 27, 37 即使我从列表中删除元素..
-
@millimoose 您可以只进行 Knuth shuffle 的前 6 次迭代,而无需继续到 45 次。