Geekpedia Programming Tutorials






Generate Random Numbers using C#

This tutorial will take you through all you need to know about generating random numbers using C#.

On Thursday, October 18th 2007 at 09:40 PM
By Andrei Pociu (View Profile)
*****   (Rated 4.8 with 8 votes)
Contextual Ads
More C# Resources
Advertisement

Pseudo-Random Numbers

Whether you're planning on building a game, looking to pick a lucky winner from an array of contest participants or simply want to display a random picture in your ASP.NET website, random numbers are something that you should know how to obtain, especially since in modern programming language it's so easy to. The dark truth behind computer generated random numbers however, is that they are not truly random, they are pseudo-random, generated by complex algorithms. But then again, for a long time scientists couldn't find anything random in the universe, and the current subjects that appear to be random are still debatable.

Without further ado, I present you what is needed in order to generate a random number in C#:


Random randNum = new Random();

randNum.Next();


That's all it takes. The creation of a Random object (of the System.Random class) and calling its Next() method, which is going to return a non-negative random number as an integer.


Random Numbers Within a Range

As soon as you test the code above, you realize it returns a quite large number. However, most of the time you'll want to generate a number between a desired range. For instance if in your contest 108 people participated, you'll want to generate a random no larger than 108:


Random randNum = new Random();

randNum.Next(108); // No larger than 108


This will generate you a positive number of up to 108, including 108. However in certain situations (such as picking the contest winner), you'll want the number to be 1 to 108, while the code above returns a number that is 0 to 108. Since people would probably not take kindly to you announcing that the winner is participant number 0, thanks to another overload of the Next() function, you will be able to specify a minimum value, as such:


Random randNum = new Random();

randNum.Next(1, 108); // No larger than 108, no smaller than 1



Using Seeds

C++ programmers and others may wonder what happened to the seed. Who's seeding this random number because you sure aren't? Well, in the default constructor of the Random() object that we've seen above, where no parameter was specified, a seed will be automatically generated for you based on the current system time (which should always be unique.) Not having to specify the system time yourself as a parameter is very convinient, since the great majority of programmers would do that when generating random numbers.

However, there are advantages to specifying your own seed. One important thing to note is that for as long as you specify the same seed, you will get the same random number. Let's look at an example:


Random randNum = new Random(1986);

randNum.Next(); // This will always generate 564610494


Here we specify a seed, more exactly the number 1986, in order to generate a random number based on that seed. However, what is the point of using this, when it always generates the same number? Check this out:


Random randNum = new Random(1986);

randNum.Next(); // This will always generate 564610494

randNum.Next(); // This will always generate 1174029081

randNum.Next(); // This will always generate 2057658224


The interesting concept behind this is that each time you apply the Next() method, it will come up with a different number, so more exactly you will get a sequence of random numbers, but since they're based on the same seed, whenever you use that seed again, you are guaranteed to get the same random numbers. Thus if we create a new Random object and pass the 1986 value, get some random values, then create another Random object and pass the same 1986 value as the seed, the same random numbers will be retrieved in the exact same sequence . I'm not going to get very deep into explaining this, but it's not hard to imagine where you would need this, and when you will need this (if ever), you'll know it.


Double-Precision Numbers

Sometimes you may want to generate double-precision numbers, and C# has a method for that. Instead of using Next(), the NextDouble() method will return a number between 0 and 1:


Random randNum = new Random();

randNum.NextDouble();

randNum.NextDouble();

randNum.NextDouble();


This will generate numbers such as 0.12820489450164194, 0.81203657295197121 and 0.0582018419231087554.

Now if you picked into IntelliSense, you've probably noticed a new method:


Array of Random Bytes

The NextBytes() method will fill an array of bytes with random bytes. Thus, each element of the array will be a byte with a value of 0 to 255:


byte[] randBytes = new byte[108];

Random randNum = new Random();

randNum.NextBytes(randBytes);


This code would produce an array with values as such: 196 231 77 225 52 144 146 72 3 90 18 233 161 205 147 196 35 152 30 220 41 114 156 25 184 185 30 64 140 138 215 62 178 90 158 94 0 47 101 234 151 44 71 189 146 113 111 90 3 93 59 104 91 143 81 82 75 51 40 123 113 81 188 121 130 212 55 71 47 52 195 243 50 52 68 252 42 222 135 70 74 196 61 46 79 111 227 34 8 75 19 205 6 234 120 70 112 206 58 190 58 39 42 206 153 71 53 38. But of course, since we don't specify a seed and the current system time is being used, you'll get a different set of values.

That's all for random numbers using C#.
Digg Digg It!     Del.icio.us Del.icio.us     Reddit Reddit     StumbleUpon StumbleIt     Newsvine Newsvine     Furl Furl     BlinkList BlinkList

Rate Rate this tutorial
Comment Current Comments
by vgstudios owner on Friday, October 19th 2007 at 12:40 PM

exelent!!!!!!!!1

by Ravi Wallau on Monday, December 3rd 2007 at 10:37 AM

private GetNextRandom() {
Random r = new Random();
int next = r.Next();
}

There are two problems with this approach:
1. The Random object is created everytime the object is called, wasting system resources;
2. The default seed is not suitable if this method is called many times in a second. Two calls in the same second will retrieve the same value from this sample, because the seed to the Random (when using the default constructor) is the current second on system time.

http://msdn2.microsoft.com/en-us/library/system.random.aspx

The best approach, in my opinion, is to create a class to generate Random numbers with static methods, and you should also have a static Random class initialized only once.

by amith on Wednesday, April 16th 2008 at 02:44 AM

I want to generate an array 5 random numbers between a range ( say min to max).

by dekidshere on Thursday, May 22nd 2008 at 01:45 AM

gak ngerti !

by ste on Thursday, July 24th 2008 at 04:19 PM

nice tutorial, tq so much.

makasih2

by ada on Wednesday, July 30th 2008 at 01:34 PM

gini aja ga ngerti... cmn kek fungsi rand di C

by cecile on Monday, August 25th 2008 at 10:47 AM

we need to write a program about poker game...and they said we're going to use random function.


Comment Comment on this tutorial
Name: Email:
Message:
Comment Related Tutorials

Random Number Generation

On Sunday, April 25th 2004 at 01:54 PM by Sean Eshbaugh in C

Random number within a range

On Tuesday, March 16th 2004 at 06:53 PM by Andrei Pociu in C++


Comment Related Source Code
There is no related source code.

Jobs C# Job Search
My skills include:
Enter a City:

Select a State:


Advanced Search >>
Latest Tech Bargains

Advertisement

Free Magazine Subscriptions

Today's Pictures

Today's Video

Other Resources

Latest Download

Latest Icons