【问题标题】:random unique number in javajava中的随机唯一数
【发布时间】:2013-01-05 18:40:51
【问题描述】:

我正在尝试获取随机数列表并将其放入队列中,而不会重复随机数。

        int number = 40;

        for (int j = 0; j<number; j++)
        {
            int pick = random.nextInt(number);
            myQueue.add(Integer.toString(pick));
        }
        System.out.println("the queue size: "+myQueue.size());
        Iterator it = myQueue.iterator();
        while(it.hasNext()){
                String iteratorValue = (String)it.next();
                System.out.println("queue next value: "+iteratorValue);
        }

使用上面的代码,我得到了一些重复的随机数

有人知道怎么做吗?

【问题讨论】:

标签: java random queue


【解决方案1】:

这个怎么样:

List<String> list = new ArrayList<String>(number);

for (int i = 0; i < number; i++)
    list.add(Integer.toString(i));

Collections.shuffle(list);

myQueue.addAll(list);

在某个范围内“添加唯一随机数”相当于将该范围内的所有数字相加,然后将结果打乱。

【讨论】:

  • anw,我在 Collections.shuffle(myQueue) 中遇到错误。我已经导入了 java.util.Collections...错误是“不适合随机播放”
  • Collections.shuffle 仅适用于 List,不适用于 Queue。也许先打乱一个列表,然后将其放入队列中?
【解决方案2】:

创建一个集合并在生成它们时将它们添加到其中。每次生成新数字时,请检查 Set 是否已包含该值。继续生成新数字并检查集合,直到找到不存在的数字。

类似这样的事情......(请注意,如果值已经在 Set 中,Set.add(...) 将返回 false,因此 do-while 循环将继续,直到生成唯一的数字。)

   int number = 40;
   Set mySet = new HashSet();
   for (int j = 0; j<number; j++)
   {
       Integer pick;

       do{
           pick = random.nextInt(number);
       } while(!mySet.add(pick));
       myQueue.add(Integer.toString(pick));
   }
   System.out.println("the queue size: "+myQueue.size());
   Iterator it = myQueue.iterator();
   while(it.hasNext()){
           String iteratorValue = (String)it.next();
           System.out.println("queue next value: "+iteratorValue);
   }

尽管如 A. R. S. 所述,您似乎不是在寻找随机的唯一数字,而是在 0 到 40 之间的所有数字的随机打乱列表。如果是这种情况,请使用他/她的解决方案这是实现该目标的更好方法。

【讨论】:

    【解决方案3】:

    如果随机数的范围很小,那么您可以简单地生成具有可用值的列表并在列表上使用Collections.shuffle

    【讨论】:

      猜你喜欢
      • 2011-12-28
      • 1970-01-01
      • 1970-01-01
      • 2012-03-14
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多