leora leora - 1 year ago 99
C# Question

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

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

Any suggestions here?

Answer Source

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);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download