Zba*_*ian 0 java sorting random unique
我想从一个区间生成随机唯一的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));
}
Run Code Online (Sandbox Code Playgroud)
我想有一个0到200之间随机排序的整数数组.我不知道为什么,但应用程序正在冻结.为什么?问题出在哪儿?
Collections.shuffle(...)随机化列表.例如:
Integer[] ids = getArrayOfNumbers();
List<Integer> idList = Arrays.asList(ids);
Collections.shuffle(idList);
ids = idList.toArray(ids);
Run Code Online (Sandbox Code Playgroud)