Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does C#'s random number generator work?

I was just wondering how the random number generator in C# works. I was also curious how I could make a program that generates random WHOLE INTEGER numbers from 1-100.

like image 632
Seth Taddiken Avatar asked Nov 24 '12 09:11

Seth Taddiken


2 Answers

You can use Random.Next(int maxValue):

Return: A 32-bit signed integer greater than or equal to zero, and less than maxValue; that is, the range of return values ordinarily includes zero but not maxValue. However, if maxValue equals zero, maxValue is returned.

var r = new Random(); // print random integer >= 0 and  < 100 Console.WriteLine(r.Next(100)); 

For this case however you could use Random.Next(int minValue, int maxValue), like this:

// print random integer >= 1 and < 101 Console.WriteLine(r.Next(1, 101);) // or perhaps (if you have this specific case) Console.WriteLine(r.Next(100) + 1); 
like image 192
Zbigniew Avatar answered Sep 30 '22 12:09

Zbigniew


I was just wondering how the random number generator in C# works.

That's implementation-specific, but the wikipedia entry for pseudo-random number generators should give you some ideas.

I was also curious how I could make a program that generates random WHOLE INTEGER numbers from 1-100.

You can use Random.Next(int, int):

Random rng = new Random(); for (int i = 0; i < 10; i++) {     Console.WriteLine(rng.Next(1, 101)); } 

Note that the upper bound is exclusive - which is why I've used 101 here.

You should also be aware of some of the "gotchas" associated with Random - in particular, you should not create a new instance every time you want to generate a random number, as otherwise if you generate lots of random numbers in a short space of time, you'll see a lot of repeats. See my article on this topic for more details.

like image 29
Jon Skeet Avatar answered Sep 30 '22 11:09

Jon Skeet