Geekpedia Tutorials Home

Building a C# Chat Client and Server

Building a C# Chat Client and ServerA step by step tutorial teaching you how to create your own chat client and chat server easily in C#, for local networks or the Internet.

in C# Programming Tutorials

Getting Hard Drive Information

Getting Hard Drive InformationA C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.

in C# Programming Tutorials

UPS Shipping Calculator

UPS Shipping CalculatorThis tutorial will teach you how to calculate the shipping cost based on the weight, height, length and depth of the box, the distance and the UPS service type.

in PHP Programming Tutorials

Create Your Own Rich Text Editor

Create Your Own Rich Text EditorCreating a Rich Text Editor using JavaScript is easier to do than you might think, thanks to the support of modern browsers; this tutorial will walk you through it.

in JavaScript Programming Tutorials
Search
Tutorials
Programming Tutorials
IT Jobs
From CareerBuilder

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 Andrew Pociu (View Profile)
*****   (Rated 4.5 with 36 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.

by Risto Karhu on Friday, January 9th 2009 at 09:38 AM

I use this for random generation. Random class should take 32 bit as random value but takes only 30 bits..dont know why. This generates random seed from system time.

1. Initalize App
2. Create Random class (only once in beginning of the app OR series of random numbers)
Random randobj = new Random(Convert.ToInt32(DateTime.Now.Ticks % 0x7FFFFFFF));
3. Exit

Works fine for me. 0x80000000 generates Overflow error. Not Random but the exakt value 0x800000.
So You should Only use values 0 to 0x7FFFFFFF as the seed. (0x7FFFFFFF = 2147483647 (decimal))

by Piotr on Monday, January 12th 2009 at 04:29 PM

Every results in this tutorial are not true. They are only true when you're debuging. Why look on
second point of Ravi Wallau comment.
This code
Random randNum = new Random();

randNum.NextDouble();

randNum.NextDouble();

randNum.NextDouble();

This will generate 3 equal doubles.

Commnet to Ravi Wallau.
"(when using the default constructor) is the current second on system time."
As far as I know is nanosecond = DataTime.Now.Ticks. However 2 point you made is correct.

My solution for finding random for some colection is pseudocode
for(int x=0;x<someCollection.length;x )
{
Random r= new Random(DateTime.Now.Ticks * (x 1));
r.getNextDouble();
}
Any ideas for more efficient solution. This solution
is wasting system resources ( random generated every step in loop).

by Piotr on Monday, January 12th 2009 at 04:32 PM

sry.. My solution is

My solution for finding random for some colection is pseudocode
for(int x=0;x<someCollection.length;x )
{
Random r= new Random(DateTime.Now.Ticks * (x 1));
r.getNextDouble();
}

.. so i'm creating seed using DateTime.Now.Ticks
and combining it with other value for each item in collection.

by Piotr on Monday, January 12th 2009 at 04:34 PM

Where da hell are " " characters

by Risto Karhu on Friday, January 16th 2009 at 05:37 AM

My solutution is for those cases you need a good "start" seed for a long series of random numbers, because the numbers in the random class is random itself. The most important thing is NOT to shuffle in the random number array BUT to get different startpoints in the random array.

So i think my solution is pretty good... i think the Random Class is misunderstood. Dont shuffle but get different starting points because the numbers NEXT to your starting poits IS random for your application.

by Risto Karhu on Friday, January 16th 2009 at 05:37 AM

My solutution is for those cases you need a good "start" seed for a long series of random numbers, because the numbers in the random class is random itself. The most important thing is NOT to shuffle in the random number array BUT to get different startpoints in the random array.

So i think my solution is pretty good... i think the Random Class is misunderstood. Dont shuffle but get different starting points because the numbers NEXT to your starting poits IS random for your application.

by Risto Karhu on Friday, January 16th 2009 at 05:45 AM

Ok...saw that now. The default constructor Takes the system time as seed.

Thats ok then. Cant see the point to shuffle .. just create the Random class with def constructor and go on with Random.next.

by Piotr on Friday, January 16th 2009 at 07:55 AM

Question to Risto Karhu:

so

Random r1 = new Random();
Random r2 = new Random();

r1.NextDouble() will give the same as r2.NextDouble()

-----
Random r1 = new Random();
double first r1.NextDouble();
double second r1.NextDouble();

first and second will give different results
?????

by Ravi Wallau on Friday, February 6th 2009 at 10:52 PM

This article has changed since I wrote my first comment a while ago, the method GetNextRandom() was removed from the code sample, which invalidates my comment in the top of this thread.

The article at MSDN provides valuable information about this: http://msdn.microsoft.com/en-us/library/system.random.aspx

Piotr, the Random class, when constructed using the default constructor (no parameters), create a random object using the default constructor that uses the system time. As the code is executed very fast, both instances are seeded with the same value, therefore generating the same sequence numbers. But if you use the same object to generate two numbers in sequence, then you will have different results.

The pseudo-random numbers (they are not truly random as they are algorithm-based, algorithm that is initialized with a number) can be used in this way when you need random numbers to build a geme or something similar. The one thing to keep in mind is that someone VERY interested in breaking on your application may guess the next random number generated by it, if he/ she knows a number of previous random numbers.

For example, if a person knows that you used the default Random constructor and that it's constructed, let's say, when the application starts, then he/ she could initialize many random classes with all the possible seeds for the past, let's say, 30 minutes, and cross that information with the numbers that your application has constructed until he/ she finds the right sequence of numbers. With that information, one could certainly guess what would be the next generated random number.

by yvisek on Saturday, March 21st 2009 at 06:22 PM

Well, when you need "realy" random numbers, you should check this: http://random.org/

cu!

by Vinod Kumar Sahu on Monday, March 30th 2009 at 01:47 AM

I get well help using this code. thanks for giving the code for random function.

by Vinod Kumar Sahu on Monday, March 30th 2009 at 01:48 AM

I get well help using this code. thanks for giving the code for random function.

by last on Saturday, August 1st 2009 at 10:45 AM

anyone know how to generate 4 digits number and also contain 4 different number in it?

by Martijn van den Enk on Friday, September 18th 2009 at 06:20 AM

Random r = new Random(); // DECLARE AS GLOBAL

private int randomNumber(int min, int max)
{
return r.Next(min, max);
}

by Kalyani on Wednesday, September 30th 2009 at 06:56 AM

This random generator was very helpfull 4 me
Thank You to Geekpedia

Thank You to all

by carlnathan on Wednesday, November 4th 2009 at 09:57 AM

mine will only show :

System.Random

in the output console...
can anyone pls help me?...

thanks

by carlnathan on Wednesday, November 4th 2009 at 09:57 AM

mine will only show :

System.Random

in the output console...
can anyone pls help me?...

thanks

by Borek on Wednesday, January 6th 2010 at 08:46 AM

mine will do the same, i dont know why.

by Borek on Monday, January 11th 2010 at 03:32 PM

I finally managed to fix the problem with System.Random, you have to generate two variables, one is for making random numbers and second is the one that you want to use:

Random anything = new Random();
int variable = anything.next(min,max);

if you want to display it for example in textbox:


Random anything = new Random();
int variable = anything.next(min,max);
anytextbox.Text= Convert.ToString(variable);

understood?

by pawan on Friday, January 22nd 2010 at 04:31 AM

Can we create random number from perticylar set of values.
For eg I want random number which should only belong to this numbers(2,8,17,15,78,54)

by Borek on Friday, January 22nd 2010 at 05:19 AM

I think that if you have only 6 numbers in set, it could be done using switch (i am not good at switch) but i think it would be like that:


//start of my code:
Random anything = new Random();
int variable = anything.next(1,6);

switch (variable)
{
case '1':
variable = 2;
break;

case '2':
variable = 8;
break;

case '3':
variable = 17;
break;

case '4':
variable = 15;
break;

case '5':
variable = 78;
break;

default:
variable = 54;
break;
}
//end of my code

this code will get you integer variable which will have amount only 2,8,17,15,78 or 54. I think you have nothing to add and it should work as it is, after that code, you can use your variable for anything you want

by Martijn van den Enk on Friday, January 22nd 2010 at 10:57 AM

Another solution would be..

//GLOBAL
Random r = new Random();
List<int> _myIntList = new List<int> { 2, 8, 17, 15, 78, 54 };

public int returnRandom()
{
return r.Next(0,5);
}

//everytime you need it, just do something like this
int myNewInt = _myIntList[returnRandom()];

by Fahmi Fauzi Rahman on Wednesday, February 17th 2010 at 06:15 PM

I have another solution and its work pretty well for me.

static uint GetRandomNumber( uint min, uint max )
{
RNGCryptoServiceProvider generator = new RNGCryptoServiceProvider();
byte[] data = new byte[1];
generator.GetBytes( data );

if( min >= max )
throw new Exception( "The minimum number must be smaller than the maximum number." );

if( min == 0 )
return Convert.ToUInt32( data[0] ) % (max 1) min;
else
return Convert.ToUInt32( data[0] ) % max min;
}

For example, if I want to generate a number between 0 or 1, it gave me a perfect result.
I've compare the result with this code:

uint result1 = GetRandomNumber( 0, 1 );

Random rng = new Random();
int result2 = rng.Next( 0, 1 );

Console.WriteLine( result1 );
Console.WriteLine( result2 );

And the result is, the Next methods from the Random class is always return 0, but the custom one is perfectly solve this problem. But now I need the faster algorithm. Can somebody help me?

by augone on Monday, March 29th 2010 at 06:45 PM

August 1st, had a few minutes, wrote these
Brute Force Method


//----------------

private bool isFourDigits( int in_val )
{
return in_val >= 1000

by Jason on Friday, April 16th 2010 at 11:12 AM

The best way to seed a random is to use a Hash on the string value of a datatime.

Random rand = new Random(DateTime.Now.ToString().GetHashCode());

by Paul on Thursday, May 27th 2010 at 05:41 AM

I am trying to develop random number generator using C#. I want to use the concepts like blocking, seed etc. Can anyone help me to start with?
Thanks

by Paul on Thursday, May 27th 2010 at 05:42 AM

I am trying to develop random number generator using C#. I want to use the concepts like blocking, seed etc. Can anyone help me to start with?
Thanks

by Borek on Thursday, May 27th 2010 at 06:21 AM

4Jason: This is what new Random() does by default isn´t it?

4Paul: What do you mean exactly? Program that allows users to generate random number by their wish?

by Paul on Thursday, May 27th 2010 at 06:32 AM

Hi Borek,
I mean block randomization and stratified randomization. I got a pdf about block randomization. I am trying to under stand it more.
I have copied the link:-
http://www.google.co.uk/search?hl=en

by Borek on Thursday, May 27th 2010 at 06:33 AM

I am sorry but that link you posted doesn´t work...

by Paul on Thursday, May 27th 2010 at 07:17 AM

Hi,
I am copying the link again-
www.lexjansen.com/pharmasug/2006/posters/po06.pdf
cheers

by Paul on Thursday, May 27th 2010 at 07:17 AM

Hi,
I am copying the link again-
www.lexjansen.com/pharmasug/2006/posters/po06.pdf
cheers


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 Andrew 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 >>
Sponsors
Discover Geekpedia

Other Resources