Question How do I create a random number between two numbers with exceptions?

Fanis

New member
Joined
Sep 6, 2015
Messages
1
Programming Experience
3-5
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?
 

JohnH

C# Forum Moderator
Staff member
Joined
Apr 23, 2011
Messages
1,183
Location
Norway
Programming Experience
10+
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];
 

wim sturkenboom

Well-known member
Joined
Aug 6, 2014
Messages
85
Location
Roodepoort, South Africa
Programming Experience
10+
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>();
            // add exceptions
            exceptions.Add(8);

            // 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
                numbers.Add(randumnumber);
            }


 
Top Bottom