【问题标题】:Best practise for random generator Java随机生成器 Java 的最佳实践
【发布时间】:2017-03-23 06:46:32
【问题描述】:

有一个数字数组,我想用随机生成器随机选择它的每个索引。随机生成器避免在已选择的索引上出现无用循环的最佳实践是什么?到目前为止,我使用一个 ArrayList 来存储已经选择的那些,但我觉得最终这个算法最终会有很多浪费的循环。代码如下:

Random r = new Random();
ArrayList<Integer> found = new ArrayList<Integer>();
while(notAllPassed){
   int prediction = r.nextInt(sizeOfArray);
   if(!found.contains(prediction){
      found.Add(prediction);
      //Do stuff
   }
}

【问题讨论】:

  • 1.建立索引列表。 2. 洗牌。
  • 稍微扩展一下@MarkoTopolnik 所说的内容(以防不明显)。搜索洗牌算法。
  • @markbernard 不需要。 Collections.shuffle()
  • 也可以使用HashSet来存储随机数,而不是先存储在ArrayList中
  • @MarkoTopolnik LOL,参加了 Collections 课程很多次,但从未注意到这一点。

标签: java arraylist random


【解决方案1】:

不要检查你是否已经生成了东西,而是以不同的方式处理它。创建一个包含所有可能值的数组,然后随机打乱该数组。

您可以使用内置方法java.util.Collection.shuffle(List)

对于初始列表,顺序无关紧要,但最简单的方法是一个接一个地填充 0..n-1 或 1..n 个值。以更复杂的方式进行操作没有任何帮助,因为 shuffle 无论如何都是完全随机的。

【讨论】:

    【解决方案2】:

    这个想法是,不是每次都选择一个随机索引,而是准备一个所有索引的打乱列表,然后按顺序对其进行迭代。

    List<Integer> indices = IntStream.range(0, sizeOfArray).boxed().collect(toList());
    Collections.shuffle(indices);
    for (int randomIndex : indices) {
       // do your thing
    }
    

    【讨论】:

      【解决方案3】:

      Marko Topolnikanswer 完全正确。这是最好的方法。

      所以我的回答只是为了完成,遵循你最初的想法Random

          Random r = new Random();                      // as you had it
          ArrayList<Integer> found = new ArrayList<>(); // as you had it
      
          for(int i = 0; i < sizeOfArray; i++){         // if you want ALL possible indexes 
              int prediction = r.nextInt(sizeOfArray);  // exactly as you did it
              while(found.contains(prediction)){        // here we check if the "found" list already contains the random index
                  prediction = r.nextInt(sizeOfArray);  // if so, regenerate the "prediction" until one is generated that is not in the list
              }
              found.add(prediction);                    // this statement will only be reached after the while loop found an index that is not in the list
          }
      
          System.out.println(found.toString());         // convenience: print the list to see for yourself 
      

      正如我所说,这只是按照您最初的想法使用随机数。如果没有Collection.shuffle(),我会这样做:)

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-25
        • 2010-11-11
        • 2020-07-29
        • 2011-07-11
        相关资源
        最近更新 更多