Thursday, March 8, 2007

System.Random is not generating Random numbers (.NET code)

Hi,
I have a scenario to generate 'N' random numbers where N is given by user.
This is the code that I have written to generate random numbers
---------------------------------------------------------------------------------------
double[] a = new double[Convert.ToInt32(txtDays.Text)];
for (int i = 0; i < Convert.ToInt32(txtDays.Text); i++)
{
Random objRandom = new Random(Convert.ToInt32(System.DateTime.Now.Ticks % System.Int32.MaxValue));
a[i] = objRandom.Next(1, 100);
}
---------------------------------------------------------------------------------------
But the above code is not giving random numbers. It seems its following a particular pattern.
;-(

Check out the code below to solve the issue:
-------------------------------------------------------------------------------------------
double[] a = new double[Convert.ToInt32(txtDays.Text)];
Random objRandom = new Random(Convert.ToInt32(System.DateTime.Now.Ticks % System.Int32.MaxValue));
for (int i = 0; i < Convert.ToInt32(txtDays.Text); i++)
{
a[i] = objRandom.Next(1, 100);
}

-------------------------------------------------------------------------------------------
So did u find the difference.
Instantiate random object only once. Dont create multiple instances of System.Random class to get random numbers.

No comments: