【问题标题】:Why does my output of randomly selected numbers contain duplicates?为什么我随机选择的数字输出包含重复项?
【发布时间】:2013-03-21 17:53:48
【问题描述】:

我的代码需要从145的列表中随机选择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 次。

标签: java random arraylist


【解决方案1】:

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

更改您的代码

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

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

【讨论】:

    【解决方案2】:

    列表维护索引,根本不关心重复元素。为避免重复,您必须使用 Set 而不是 List。如果您在 Set 中有任何用户定义的类,那么不要忘记实现 equals() 和 hashcode(),它们用于确定元素是否由 Set 类(如 HashSet)重复或不重复。

    如果您的 Set 中有原语,那么请忘记重复,因为对于 int、long 等原始数据类型,将自动处理重复。所以我建议您使用 Set 而不是 List。避免集合中的重复元素

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-21
      • 1970-01-01
      • 1970-01-01
      • 2020-02-22
      • 2013-03-19
      相关资源
      最近更新 更多