Random generators
Wed, 12 Mar 2008 01:15:58 +0000 - Author: Peter O.
There are many programs out there that teach computers to generate random numbers, ranging from Visual Basic's generator to the Mersenne Twister. The following code contains a C# interface and class that you can use to experiment with the different generators.
public interface IRandom {
// Returns a random number.
int Next();
// Fills an array with random bytes.
void NextBytes(byte[] bytes);
// Returns a positive integer less than maxValue.
int Next(int maxValue);
// Returns a positive integer from minValue and less than maxValue.
int Next(int minValue, int maxValue);
// Returns a double from 0 through 1.
double NextDouble();
}
And this class is a base for implementing custom random number algorithms. Derived classes need implement only the next function, RandomBase will implement the rest. Some ideas for the methods' implementations were taken from this article.
public abstract class RandomBase : IRandom { protected RandomBase(){ } protected RandomBase(int seed){ } public abstract int Next(); public double NextDouble(){ return (((double) (uint) this.Next()) / 4294967295.0); } public int Next(int maxValue){ return Next(0,maxValue); } public void NextBytes(byte[] buffer){ if (buffer == null) throw new ArgumentNullException("buffer"); int value = 0; for (int i = 0; i < buffer.Length; i++){ if ((i & 3) == 0){ value = this.Next(); } buffer[i] = (byte) (value & 0xff); value = value >> 8; } } public int Next(int minValue, int maxValue){ if ( minValue > maxValue ) throw new ArgumentOutOfRangeException("minValue"); if(minValue==maxValue)return minValue; long diff=maxValue-minValue; long max=0x100000000L; long remainder=max%diff; while(true){ uint rnd=(uint)this.Next(); if(rnd<max-remainder) { return (int)(minValue+(rnd%diff)); } } } }