Random Numbers

Random numbers are tricky things. If they are predictable, they are very dangerous if used in public applications (or private applications) since someone may try and figure out the pattern. Unfortunately, truely random numbers are hard to generate and often rely on physical media for their creation (neutrinos and such). Thus, pseudo-random numbers are often used in programming and simulation. Pseudo-random numbers are generated from a long list of numbers (look in the back of a stats book and see an example). You start at some arbitrary point (this is called a seed) and keep moving from there.

In C#, you can easily use the Random class to generate primitives of the random type. These are pseudo-random numbers which are seeded from the system time. Be very careful about this since there are numerous ways to cause problems. The most common is to instantiate your randoms inside a loop:

 

while (true)

{

Random myRand = new Random();

Console.WriteLine(myRand.Next(0,500).ToString());

}

This generates a string of numbers but look at how seldom they change. This is due to the instantiation of many different objects all with the same seed. The reason for the seeding is to allow for the reproducibility of a given simulation (to prove something you need to be able to demonstrate the results). Thus, you could always start with the same seed and get the same set of results. Unfortunately, in a game like roulette, this would be disasterous! Within a few trials, users would figure out the pattern and your game would have a serious problem. Watch this:

Random myRand = new Random();

while (true)

{

Console.WriteLine(myRand.Next(0,500).ToString());

}

Now, only a single random object is instantiated but it is continually flipping through the list. It will be much harder for someone to analyze this and come up with a pattern.

Even if you have many different random events going on, use the same random with .next after it. Don't build multiple random objects for basic problems.

There are other problems with Random such as Race Track Attacks and Thread Attacks where hackers will attack your application and take advantage of this weak class. Thus, there are other solutions. Add System.Security.Cryptotography to your program (using System.Security.Cryptography;) (see http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpref/html/frlrfsystemsecuritycryptographyrngcryptoserviceproviderclasstopic.asp . This creates a new class called RandomNumberGenerator that is much more robust than Random. Now, you can use it like this:

byte[] myBetterRand = new byte[1];
RNGCryptoServiceProvider getIt = new RNGCryptoServiceProvider();
getIt.GetBytes(myBetterRand);

int theAnswer = Convert.ToInt32(myBetterRand[0]);
Console.WriteLine(theAnswer % 37);

The Answer should have 0 to 36 in it for your enjoyment and be a fairly random approach. You can certainly test it for extra credit.