I created a random number generator for an application that uses a
MersenneTwister class I found on the net. Basically I generate two
random numbers from the MersenneTwister class and use each one as a
seed for the built in Random class of the .net framework. To better
illustrate I am prodviding the complete code for this application, it
isn't too much but I would like to know if this is a viable solution
because I am a pretty new to C# and programming so please any negative
or positive criticism is welcome.
// begin
public sealed class Program
{
static Random mt_r1;
static Random mt_r2;
static readonly string spChars =
@"ABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890!@#$%^&*()<> ,.?/|\{}[]+=_-
abcdefghijklmnopqrstuvwxyz";
const string intNums = @"0123456789";
const string path = @"C:\";
const string fileName = @"rng.txt";
// Length of the number generated
const int rLen = 20;
// How many random numbers to generate
const int rNum = 20;
static void Main(string[] args)
{
try
{
// Create an instance of the MersenneTwister class
MersenneTwister randGen = new MersenneTwister();
// Create a new instance of FileStream to create the
flat file for writing
FileStream fs = new FileStream(path + fileName,
FileMode.Create);
// StreamWriter class to write the file stream
StreamWriter sw = new StreamWriter(fs);
// Append header information to the top of the file
sw.WriteLine("id,random_num");
for (int i = 0; i < rNum; ++i)
{
// Create an instance of the Random class using
the
// MersenneTwister value as the seed and assign
the value
mt_r1 = new Random(randGen.Next());
// Create another instance of the Random class
// with a new MersenneTwister value as the seed
and assign
mt_r2 = new Random(randGen.Next());
// Write an id number and random string to file
sw.WriteLine(i + "," + Randomize(spChars, rLen));
}
// Close the stream writer
sw.Close();
}
catch
{
}
}
/// <summary>
/// Randomizes a number set using the Random class
/// and the MersenneTwister algorithm
/// </summary>
/// <param name="characters">Character set.</param>
/// <param name="length">Length of the random string</param>
public static string Randomize(string characters, int length)
{
// Create a char array with a size of the given length
char[] ret = new char[length];
// iterate through the array
for (int i = 0; i < length; i++)
{
// If 'i' is an even number, fill the corresponding
index
// with a value from the randomized character set
if (i % 2 == 0)
{
ret[i] =
characters[mt_r1.Next(characters.Length)];
}
// Fill odd numbered indices with randomized character
from the set
else if (i % 2 == 1)
{
ret[i] =
characters[mt_r2.Next(characters.Length)];
}
}
// Return the new randomized string
return new string(ret);
}
}
// end