java根据最⼩值和最⼤值⽣成指定个数不重复的随机数(指定
n个数量)
代码随机⽣成count个不重复的随机数,平均数约(max-min)/count。
⽬前有遍历list、遍历int[]、使⽤HashSet去重list返回、使⽤set去重int[]返回、使⽤LinkedHashSet
⾸先list效率肯定⽐int[]低,所以遍历list、HashSet+List⼀定⽐另2个低。LinkedHashSet返回时需要转成list或int[]⽤处不⼤
所以推荐使⽤的有:
①如果count都⼩于100,则遍历int[]效率及内存最优
②如果count有⼤于100的,推荐HashSet+int[]组合(如果不清楚,推荐使⽤此⽅式)
遍历list效率⼀直是最差的,不推荐使⽤
/**
* 随机count个不重复数据,包含min和max
* HashSet+int[]组合,推荐使⽤
*/
public static int[] randomNoRepeatSetInt(int min, int max, int count) {
if (count < 1) {
throw new IllegalArgumentException("count必须⼤于0");
}
if (max + 1 - min < count) {
throw new IllegalArgumentException("范围必须⼤于count,不然怎么不重复?");
}
Random random = new Random();
HashSet<Integer> set = new HashSet<>(count);
java生成随机数的方法int[] ints = new int[count];
while (set.size() < count) {
int next = nextNum(random, min, max);
if (set.add(next)) {
ints[set.size() - 1] = next;
}
}
return ints;
}
/**
* 随机count个不重复数据,包含min和max
* 遍历int[],count<100时内存效率最优
*/
public static int[] randomNoRepeatInt(int min, int max, int count) {
if (count < 1) {
throw new IllegalArgumentException("count必须⼤于0");
}
if (max + 1 - min < count) {
throw new IllegalArgumentException("范围必须⼤于count,不然怎么不重复?");
}
Random random = new Random();
int[] ints = new int[count];//此处也可以直接⽤int数组
int size = 0;
continueThis:
while (size < count) {
int next = nextNum(random, min, max);
for (int i = 0; i < size; i++) {
if (ints[i] == next) {
continue continueThis;//继续while
}
}
ints[size] = next;
ints[size] = next;
size++;
}
return ints;
}
/**
* 随机count个不重复数据,包含min和max
* 遍历List,效率⼀直最差,不推荐使⽤
*/
public static List<Integer> randomNoRepeatList(int min, int max, int count) {
if (count < 1) {
throw new IllegalArgumentException("count必须⼤于0");
}
if (max + 1 - min < count) {
throw new IllegalArgumentException("范围必须⼤于count,不然怎么不重复?");
}
Random random = new Random();
ArrayList<Integer> list = new ArrayList<>(count);
while (list.size() < count) {
int next = nextNum(random, min, max);
if (!ains(next)) {
list.add(next);
}
}
return list;
}
private static int nextNum(Random random, int min, int max) {
Int(max + 1 - min) + min;
}
当然你也可以只⽤list然后遍历判断是否包含,感觉上节约个set对象,但你可以试试20个以上的数据我打包票上⾯最快 随机单条数据:
/**
* 范围内随机⼀个值,包含min和max
*/
public static int nextNum(int min, int max) {
if (max <= min) {
throw new IllegalArgumentException("max必须⼤于min");
}
return nextNum(new Random(), min, max);//见上⾯的⽅法
}
可重复的就不多说了吧,直接fori然后nextNum就⾏了

版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。