# QuestionHow do I create a random number between two numbers with exceptions?

#### Fanis

##### New member
I wanna generate a random number between 1 and 10 that doesn't equal 8, for example.

C#:
``````[COLOR=#000000][FONT=Helvetica]            Random rnd = new Random();[/FONT][/COLOR]
[COLOR=#000000][FONT=Helvetica]            int a = rnd.Next(1,11);[/FONT][/COLOR]``````
this will generate a random number between 1 and 10, but how can I set it not to equal 8?
I know I can do

C#:
``````[COLOR=#000000][FONT=Helvetica]Start:[/FONT][/COLOR]
[COLOR=#000000][FONT=Helvetica]            Random rnd = new Random();[/FONT][/COLOR]
[COLOR=#000000][FONT=Helvetica]            int a = rnd.Next(1,11);[/FONT][/COLOR]
[COLOR=#000000][FONT=Helvetica]            if(a == 8){[/FONT][/COLOR]
[COLOR=#000000][FONT=Helvetica]               goto Start;[/FONT][/COLOR]
[COLOR=#000000][FONT=Helvetica]           }[/FONT][/COLOR]``````

but when it comes to many variables and many exceptions it's very time consuming. Is there a better way to do this?

You could populate a list/array with the options/ranges, and select one of those by random index.
```            var options = Enumerable.Range(1, 10).ToList();
options.Remove(8);
var ix = rnd.Next(0, options.Count);
var value = options[ix];```

I use something like below often; instead of exceptions, I often examine the list to make sure that a random number does not occur twice

```            // list to hold exceptions
List<int> exceptions = new List<int>();

// random number generator
Random rnd = new Random();

// list to hold generated numbers
List<int> numbers = new List<int>();
// populate list
while (numbers.Count != 10)
{
// get a random number
int randumnumber = rnd.Next(1, 11);
// if in list of exceptions, try again
if (exceptions.Contains(randumnumber))
continue;
// add to list of random numbers
}

```

Replies
4
Views
491
Replies
1
Views
885
Replies
24
Views
2K
Replies
5
Views
530
Replies
9
Views
2K