【问题标题】:Java generating random unique numbers from an interval of numbersJava从数字区间生成随机唯一数字
【发布时间】:2013-02-14 00:17:43
【问题描述】:

我想从一个区间生成随机的唯一 int 数,但应用程序冻结了(无限循环)。

int[] ids = new int[200];
for(int i = 0; i < ids.length; i++){
   int temp = getUnique(ids);
   ids[i] = temp;
}

private int getUnique(int[] ids){
   while(true){
      int iRand = random(0, ids.length);
      if( unique( ids, iRand ) ) return iRand;
   }
}

private boolean unique(int[] arr, int i){
    for(int k : arr){
        if(k == i) return false;
    }

    return true;
}

private int random(int Min, int Max){
   return Min + (int)(Math.random() * ((Max - Min) + 1));
}

我想要一个随机排序的 0 - 200 之间的整数数组。我不知道为什么,但应用程序正在冻结。为什么?问题出在哪里?

【问题讨论】:

  • 除了你得到的答案,你的程序对我来说很好。我无法重现您的问题。

标签: java sorting random unique


【解决方案1】:

考虑使用Collections.shuffle(...) 随机化一个列表。

例如:

Integer[] ids = getArrayOfNumbers();
List<Integer> idList = Arrays.asList(ids);
Collections.shuffle(idList);
ids = idList.toArray(ids);

【讨论】:

  • 是的,基本思想是创建一个从 1 到 200 的整数数组,将它们打乱,然后一个一个地遍历它。这将为您提供区间 (1-200) 内的 200 个随机整数
【解决方案2】:

我建议你将你想要的数字插入到排序后的数组中,然后将它们打乱,因为生成一个随机数然后检查它是否唯一可能需要很长时间..

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-03
    • 2013-07-20
    • 1970-01-01
    • 1970-01-01
    • 2011-08-18
    • 2012-06-05
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多