生成除某些值以外的随机数 [英] Generate random numbers except certain values
本文介绍了生成除某些值以外的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想生成随机数,但不希望它们来自 exclude
数组.这是我的代码.
I want to generate random numbers, but don't want them to be from exclude
array. Here is my code.
public int generateRandom(int start, int end, ArrayList<Integer> exclude) {
Random rand = new Random();
int range = end - start +1 - exclude.size();
int random = rand.nextInt(range) + 1;
for(int i = 0; i < exclude.size(); i++) {
if(exclude.get(i) > random) {
return random;
}
random++;
}
return random;
}
我在 while 循环中使用此函数,并在每次迭代期间向 exclude
添加一个新值.有时它返回属于exclude
的数字.有什么问题?
I use this function in a while loop, and during each iteration I add a new value to exclude
.
Sometimes it returns numbers that belong to exclude
. What's the problem?
推荐答案
if(!exclude.contains(random))
return random;
每次都会返回不在 exclude 中的值时尝试此操作.
Try this every time it will return the value that is not in exclude.
这篇关于生成除某些值以外的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文