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?
Consider using
Collections.shuffle(...)to randomize a list.For example: