Although you can use List list the numbers you want to generate and exclude / delete the one you want to exclude, this is only effective for small ranges. If you want to generate a random number in a large range, this solution becomes quite inefficient and impracticable.
Solution using only 1 Random.nextInt() call
If you want to generate random numbers in the range 0..5 inclusive, you can do this with r.nextInt(6) .
If you want to exclude a number, for example. 4 , this means that the range is less than 1, so use r.nextInt(5) , and if the result is an excluded number, return the maximum allowable max 5 (because it will never be generated because you used max - 1).
It looks like this:
// Returns a random number in the range 0..5 (0 and 5 included), 4 excluded public int nextRand() { int i = r.nextInt(5); return i == 4 ? 5 : i; }
Common decision
Here is a general solution that takes min , max and excluded numbers as parameters:
public int nextRand(int min, int max, int excluded) { if (max <= min || excluded < min || excluded > max) throw new IllegalArgumentException( "Must be: min <= excluded <= max AND min < max"); int i = min + r.nextInt(max - min);
So, for example, if you call nextRand(0, 5, 3) , it returns only a random number, which is one of 0, 1, 2, 4, 5 .
source share