问题
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