代码来自:https://www.cnblogs.com/ningvsban/p/3590722.html,感觉实现的方式不错(做了一点小小修改)
public static ArrayList getDiffNo(int count, int n){ // 生成count个[0-n) 不重复的随机数,左开右闭 // list 用来保存这些随机数 ArrayList list = new ArrayList(); Random rand = new Random(); boolean[] bool = new boolean[n]; int num = 0; for (int i = 0; i < count; i++) { do { // 如果产生的数相同继续循环 num = rand.nextInt(n); } while (bool[num]); bool[num] = true; list.add(num); } return list; }
测试:
for (int i = 0; i < 10; i++) { System.out.println(getDiffNo(5, 20));; }
结果:
[4, 0, 8, 9, 13] [6, 13, 8, 10, 14] [16, 6, 17, 12, 19] [3, 10, 13, 4, 14] [10, 0, 1, 5, 19] [1, 14, 5, 11, 6] [1, 3, 5, 9, 18] [0, 5, 10, 4, 7] [4, 5, 19, 10, 16] [6, 13, 11, 3, 18]
原文地址:https://www.cnblogs.com/huigelaile/p/11002285.html
时间: 2024-10-10 07:12:04