# How can I exclude a range of values when generating random numbers?

If you are using Random.range to generate values, is there any way to exclude some values within the range (for example: pick a number between 1 and 20, but not 6 through 8)?

Instead of throwing away numbers you don't want, you can pretend you want a number from one slightly smaller range, and then map it into the 2 ranges you want:

float val = Random.Range( 1, 20 - 8 + 6 );
if ( val >= 6 ) val += 2;

• This is clever and probably the best solution. – jgallant Jun 17 '16 at 10:52
• the problem is that this becomes a code mess when you want to work with multiple excluded ranges and variable ranges. – Nzall Jun 17 '16 at 11:04

You could generate a list of values you want to use, and then pick one at random.

Create values:

int[] values = new int[17] { 0,1,2,3,4,5,6,7,10,11,12,13,14,15,16,17,18,19,20 };


Get a random value:

   int value = values[Random.Range(0, values.Length)];

• What if the OP wants to generate a random number between 10 and 100? You're going to create an array containing those 90 numbers? – user85869 Jun 17 '16 at 10:41
• I probably wouldnt create an array with the values no, more than likely not depending on the case. – jgallant Jun 17 '16 at 10:43
• Your answer shows otherwise – user85869 Jun 17 '16 at 10:44
• I am providing a solution to his question, you dont have to get all upset over this. – jgallant Jun 17 '16 at 10:45

I guess you should go with a solution like this:

    int[] validChoices = new int[n]= {1,3,5, whatever until n occurrences};

private int GetRandom(){
return validChoices[Random.Range(0, validChoices.Length)];
}