import java.util.*;
public class UniqueRandomNumbers {
public static int[] generateUnique(int min, int max, int count) {
if (count > max - min + 1) throw new IllegalArgumentException("數量超過範圍");
Set<Integer> set = new HashSet<>();
Random rand = new Random();
while (set.size() < count) {
set.add(rand.nextInt(max - min + 1) + min);
}
return set.stream().mapToInt(Integer::intValue).toArray();
}
public static void main(String[] args) {
int[] res = generateUnique(1, 150, 100);
Arrays.sort(res);
for (int n : res) System.out.println(n);
}
}
Random.nextInt(bound) 生成 [0, bound),+min 映射到 [min, max]HashSet 自動去重,size() 達標即停止count / (1 - count/range),此處範圍 150,取 100,效率可接受count 接近 range,建議改用 **洗牌算法**:生成全範圍列表 Collections.shuffle 取前 count 個,O(N) 確定性
public static int[] generateByShuffle(int min, int max, int count) {
List<Integer> pool = new ArrayList<>(max - min + 1);
for (int i = min; i <= max; i++) pool.add(i);
Collections.shuffle(pool);
return pool.subList(0, count).stream().mapToInt(Integer::intValue).toArray();
}
程序輸出 100 個 1-150 間不重複整數,排序後顯示。