javarandom

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?


Solution

  • 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.