所以我試圖生成一個填充有唯一隨機整數的陣列,我發現使用 arraylist 執行此操作將是最有效的方法。
public static int [] randArr(int n, int max){
randArr = new int[n];
Random rn = new Random();
Set<Integer> test = new HashSet<Integer>();
while(test.size() < n){
test.add(rn.nextInt(0, max));
}
}
現在我嘗試使用,randArr = test.toArray()但我不太確定在括號中放什么,或者這是否真的可以作業。是否有任何其他轉換方法,因為我也不能通過test.get(i)for 回圈簡單地將 randArr 分配給 test 的整數。
uj5u.com熱心網友回復:
不要使用一套。Stream亂數,使用 洗掉重復distinct,并限制使用limit
public static int [] randArr(int n, int max){
Random rn = new Random();
return rn.ints(0,max).distinct().limit(n).toArray();
}
筆記:
- 確保這一點
n is <= max,否則您可能會等待一段時間。 max must be >= 1(Random.ints方法要求)
您可能需要輸入一些代碼來強制執行這些代碼,invariants如果不合規則拋出適當的例外。類似于以下內容(或任何對您有意義的內容)。
if (n > max || max <= 0) {
throw new IllegalArgumentException(
"n(%d) <= max(%d) or max > 0 not in compliance"
.formatted(n,max));
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/466265.html
上一篇:如何從2個陣列創建嵌套資料結構?
