A 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.
A C# tutorial showing you how to make use of WMI to extract information on disk drives, such as model, capacity, sectors and serial number.
This 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.
Creating 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.
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) |
||
Pseudo-Random NumbersWhether 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.
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: |
|||
Digg It!
Del.icio.us
Reddit
StumbleIt
Newsvine
Furl
BlinkList
|
|||
|
|||
Current Commentsexelent!!!!!!!!1
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.
I want to generate an array 5 random numbers between a range ( say min to max).
gak ngerti !
nice tutorial, tq so much.
makasih2
gini aja ga ngerti... cmn kek fungsi rand di C
we need to write a program about poker game...and they said we're going to use random function.
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))
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).
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.
Where da hell are " " characters
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.
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.
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.
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
?????
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.
Well, when you need "realy" random numbers, you should check this: http://random.org/
cu!
I get well help using this code. thanks for giving the code for random function.
I get well help using this code. thanks for giving the code for random function.
anyone know how to generate 4 digits number and also contain 4 different number in it?
Random r = new Random(); // DECLARE AS GLOBAL
private int randomNumber(int min, int max)
{
return r.Next(min, max);
}
This random generator was very helpfull 4 me
Thank You to Geekpedia
Thank You to all
mine will only show :
System.Random
in the output console...
can anyone pls help me?...
thanks
mine will only show :
System.Random
in the output console...
can anyone pls help me?...
thanks
mine will do the same, i dont know why.
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?
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)
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
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()];
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?
August 1st, had a few minutes, wrote these
Brute Force Method
//----------------
private bool isFourDigits( int in_val )
{
return in_val >= 1000
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());
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
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
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?
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
I am sorry but that link you posted doesn´t work...
Hi,
I am copying the link again-
www.lexjansen.com/pharmasug/2006/posters/po06.pdf
cheers
Hi,
I am copying the link again-
www.lexjansen.com/pharmasug/2006/posters/po06.pdf
cheers
Related Tutorials
Related Source Code
C# Job Search