How can I generate a random number from two different ranges?
For example: one number from 10-20 and 50-60.
I know how to generate a random number from one range (1-13):
Random rnd = new Random();
int num = rnd.Next(1, 13);
int num = rnd.Next(1, 3)==1 ? rnd.Next(10, 21) : rnd.Next(50,61);
or
int num = rnd.Next(10, 32);
if (num>20) num+=29;
or just for fun (don't use with large ranges, and runs slow anyhow):
var ranges=new []{ Tuple.Create(10,20), Tuple.Create(50,60)};
var rnd=new Random();
var possible=ranges.Select(x=>Enumerable.Range(x.Item1,x.Item2-x.Item1+1))
.SelectMany(x=>x)
.Distinct();
var num=possible.Skip(rnd.Next(0,possible.Count())).First();
Remember for the Next method, the lower bound is inclusive, while the upper bound is exclusive. How about:
var rand = new Random();
var num1 = rand.Next(10, 21);
var num2 = rand.Next(50, 61);
var myNum = rand.Next(0, 2) == 1 ? num1 : num2;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With