Random for .NET - Games and More
I started writing a brain games software which will be used for brain training and allow the user to take courses that will enhance and sharpen different abilities such as memory and attention. While writing Brain Games and testing my games I came across a disturbing phenomena: The .NET random (System.Random) is not really random. When I randomly set items similar ones appear next to each other and games look bad.
After searching the internet I came across the suggestion to use the RNGCryptoServiceProvider in order to generate random bytes. The examples found on StackOverFlow and other places seem to be good for a single bye only so I decided to publish the changes I made.
The code includes a RandomX class that uses the above crypto service provider. This code is much slower than the System.Random but it has much better results:
public class RandomX
{
static RNGCryptoServiceProvider Gen = new RNGCryptoServiceProvider();
public RandomX()
{
}
public int Next(int pMin, int pMax)
{
int normTo = pMax - pMin;
// Create a byte array to hold the random value.
byte[] randomNumber = new byte[4];
// Create a new instance of the RNGCryptoServiceProvider.
// Fill the array with a random value.
Gen.GetBytes(randomNumber);
// Convert the byte to an integer value to make the modulus operation easier.
int rand = (int)BitConverter.ToUInt32(randomNumber, 0);
// Return the random number mod the number
// of sides. The possible values are zero-
// based, so we add one.
return (Math.Abs(rand % normTo) + pMin);
}
}