Random number generator only generating one random number

R

To generate a random number it involves instantiating the Random class then calling the Next function with a minimum and maximum value as follows: new Random().Next(min, max) so why is it always returning the same number? This commonly occurs when this is being called in a loop.

Here is an example function that generates a random number with how it is being called in a loop:

[code]
public static int RandomNumber(int min, int max)
{
Random random = new Random();
return random.Next(min, max);
}

for (var i = 0; i < 5; i++) { var randomNumber = RandomNumber(0, i); // Do something with the number } [/code] Now because the call to the random number generator is in a loop that executes in milliseconds, when the RandomNumber class is instantiated it is seed with the current date time. Inside the loop this happens so fast that it is always the same seed causing the same number generated each time.

Avoiding duplicate Random Numbers

Let’s alter the existing code to maintain a static reference to the Random class so that when we call Next it is smart enough to not generate the same number on the first call:

[code]
private static Random random = new Random();

public static int RandomNumber(int min, int max)
{
return random.Next(min, max);
}

for (var i = 0; i < 5; i++) { var randomNumber = RandomNumber(0, i); // Do something with the number } [/code] If this code has a chance of being called concurrently it might be a good idea to include a lock on the function so it prevents calling Next at the exact millisecond because we are accessing a static object: [code] private static Random random = new Random(); private static object randomLock = new object(); public static int RandomNumber(int min, int max) { lock (randomLock) { return random.Next(min, max); } } for (var i = 0; i < 5; i++) { var randomNumber = RandomNumber(0, i); // Do something with the number } [/code] With the lock (randomLock) any concurrent calls will have a slight wait before executing the call until the lock has been release on the randomLock object.

Other useful articles

About the author

By Jamie

My Books