如何在一个范围内生成一个随机数但排除一些? [英] How can I generate a random number within a range but exclude some?
问题描述
如何在一个范围内生成随机数但排除一些,而不继续生成并检查生成的数字是否是我要排除的数字之一?
How can I generate a random number within a range but exclude some, without keep generating and checking if the generated number is one of those that I want to exclude?
推荐答案
每次随机无重生的一种可能解决方案是使用以下算法:
One possible solution without regeneration the random each time is to use the following algorithm:
public int getRandomWithExclusion(Random rnd, int start, int end, int... exclude) {
int random = start + rnd.nextInt(end - start + 1 - exclude.length);
for (int ex : exclude) {
if (random < ex) {
break;
}
random++;
}
return random;
}
可以使用数组引用调用此方法,例如
This method can be either called with an array reference, e.g.
int[] ex = { 2, 5, 6 };
val = getRandomWithExclusion(rnd, 1, 10, ex)
或直接插入号码进入通话:
or by directly inserting the numbers into the call:
val = getRandomWithExclusion(rnd, 1, 10, 2, 5, 6)
它在 start
和<$之间生成一个随机数(int) c $ c>结束(包括两者)并且不会为您提供数组 exclude
中包含的任何数字。所有其他数字的概率相等。请注意,必须保留以下约束: exclude
按升序排序,所有数字都在提供的范围内,并且所有数字都是相互不同的。
It generates a random number (int) between start
and end
(both inclusive) and does not give you any number which is contained in the array exclude
. All other numbers occur with equal probability. Note, that the following constrains must hold: exclude
is sorted ascendingly and all numbers are within the range provided and all of them are mutually different.
这篇关于如何在一个范围内生成一个随机数但排除一些?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!