Follow @endyourif rss Facebook LinkedIn

Random number generator only generating one random number Random number generator only generating one random number

Published on Mar 3, 2020

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:


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
}


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:


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
}


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:


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
}


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.

Tags: ASP.NET MVC and Web API Tutorial | c#

My Books
ASP.NET MVC 5 With Bootstrap and Knockout.js
Knockout.js Building Dynamic Client-Side Applications
20 Recipes for Programming MVC 3
20 Recipes for Programming PhoneGap
Rapid Application Development with CakePHP