Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate random number from 2 different ranges

Tags:

c#

random

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);
like image 788
Avraham Sikirov Avatar asked Dec 24 '22 12:12

Avraham Sikirov


2 Answers

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();
like image 191
Robert McKee Avatar answered Jan 15 '23 17:01

Robert McKee


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;
like image 27
Sean Avatar answered Jan 15 '23 19:01

Sean