How do I seed a random class to avoid getting duplicate random values

C#Random

C# Problem Overview


I have the following code inside a static method in a static class:

Random r = new Random();
int randomNumber = r.Next(1,100);

I have this inside a loop and I keep getting the same randomNumber!

Any suggestions here?

C# Solutions


Solution 1 - C#

A good seed generation for me is:

Random rand = new Random(Guid.NewGuid().GetHashCode());

It is very random. The seed is always different because the seed is also random generated.

Solution 2 - C#

You should not create a new Random instance in a loop. Try something like:

var rnd = new Random();
for(int i = 0; i < 100; ++i) 
   Console.WriteLine(rnd.Next(1, 100));

The sequence of random numbers generated by a single Random instance is supposed to be uniformly distributed. By creating a new Random instance for every random number in quick successions, you are likely to seed them with identical values and have them generate identical random numbers. Of course, in this case, the generated sequence will be far from uniform distribution.

For the sake of completeness, if you really need to reseed a Random, you'll create a new instance of Random with the new seed:

rnd = new Random(newSeed);

Solution 3 - C#

Bit late, but the implementation used by System.Random is Environment.TickCount:

public Random() 
  : this(Environment.TickCount) {
}

This avoids having to cast DateTime.UtcNow.Ticks from a long, which is risky anyway as it doesn't represent ticks since system start, but "the number of 100-nanosecond intervals that have elapsed since 12:00:00 midnight, January 1, 0001 (0:00:00 UTC on January 1, 0001, in the Gregorian calendar)".

Was looking for a good integer seed for the TestApi's StringFactory.GenerateRandomString

Solution 4 - C#

In case you can't for some reason use the same Random again and again, try initializing it with something that changes all the time, like the time itself.

new Random(new System.DateTime().Millisecond).Next();

Remember this is bad practice though.

EDIT: The default constructor already takes its seed from the clock, and probably better than we would. Quoting from MSDN: > Random() : Initializes a new instance of the Random class, using a time-dependent default seed value.

The code below is probably your best option:

new Random().Next();

Solution 5 - C#

public static Random rand = new Random(); // this happens once, and will be great at preventing duplicates

Note, this is not to be used for cryptographic purposes.

Solution 6 - C#

this workes for me:

private int GetaRandom()
	{
		Thread.Sleep(1);
		return new Random(DateTime.Now.Millisecond).Next();
	}

Solution 7 - C#

A good seed initialisation can be done like this

Random rnd = new Random((int)DateTime.Now.Ticks);

The ticks will be unique and the cast into a int with probably a loose of value will be OK.

Solution 8 - C#

I use this for most situations, keep the seed if there is a need to repeat the sequence

    var seed = (int) DateTime.Now.Ticks;
    var random = new Random(seed);

or

    var random = new Random((int)DateTime.Now.Ticks);

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionleoraView Question on Stackoverflow
Solution 1 - C#joppiesausView Answer on Stackoverflow
Solution 2 - C#mmxView Answer on Stackoverflow
Solution 3 - C#OrphidView Answer on Stackoverflow
Solution 4 - C#PPCView Answer on Stackoverflow
Solution 5 - C#McKayView Answer on Stackoverflow
Solution 6 - C#OmidooView Answer on Stackoverflow
Solution 7 - C#ZedZedView Answer on Stackoverflow
Solution 8 - C#Gary DaviesView Answer on Stackoverflow