Java generating random unique numbers from an interval of numbers

安稳与你 提交于 2019-12-13 04:28:16

问题


I want to generate random unique int numbers from an interval but the app freezes out (infinite loop).

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));
}

I would like to have an array of integers between 0 - 200 sorted randomly. I don't know why, but the application is freezing out. Why? Where is the problem?


回答1:


Consider using Collections.shuffle(...) to randomize a list.

For example:

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



回答2:


I suggest you insert numbers you want into that array sorted and then shuffle them, since generating a random number and then checking whether it is unique or not might take a very long time..



来源:https://stackoverflow.com/questions/14865739/java-generating-random-unique-numbers-from-an-interval-of-numbers

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!