Create multiple Random instances with different seeds
suggest changeOn .NET Framework, two Random instances created in the same clock tick share a seed, so they produce the same sequence. Later runtimes pick a different seed for each parameterless Random.
Guid.NewGuid().GetHashCode() usually differs from call to call. Hash codes can still collide, so it is not a guaranteed unique seed.
Random rnd1 = new Random();
Random rnd2 = new Random();
Console.WriteLine("First 5 random numbers in rnd1");
for (int i = 0; i < 5; i++)
Console.WriteLine(rnd1.Next());
Console.WriteLine("First 5 random numbers in rnd2");
for (int i = 0; i < 5; i++)
Console.WriteLine(rnd2.Next());
rnd1 = new Random(Guid.NewGuid().GetHashCode());
rnd2 = new Random(Guid.NewGuid().GetHashCode());
Console.WriteLine("First 5 random numbers in rnd1 using Guid");
for (int i = 0; i < 5; i++)
Console.WriteLine(rnd1.Next());
Console.WriteLine("First 5 random numbers in rnd2 using Guid");
for (int i = 0; i < 5; i++)
Console.WriteLine(rnd2.Next());
Another way to achieve different seeds is to use another Random instance to retrieve the seed values.
Random rndSeeds = new Random();
Random rnd1 = new Random(rndSeeds.Next());
Random rnd2 = new Random(rndSeeds.Next());
This also makes it possible to control the result of all the Random instances by setting only the seed value for the rndSeeds. All the other instances will be deterministically derived from that single seed value.
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents