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)
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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…