0

Possible Duplicate:
why does this method return the same random string each time?
Random not that random

I have weird behavior in this code.

public void InitPopulation()
{
    for (int i = 0; i < PopSize; i++)
    {
        var builder = new StringBuilder();
        var random = new Random();

        for (int j = 0; j < Target.Length; j++)
        {
            builder.Append(Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))));
        }

                        vector.Add(new GaStruct() { Fitness = 0, StrValue = builder.ToString().ToLower() });
        builder.Clear();
    }
}

This code gives me 5 absolutely identical strings!

If I add the Thread.Sleep like this:

public void InitPopulation()
{
    for (int i = 0; i < PopSize; i++)
    {
        var builder = new StringBuilder();
        var random = new Random();

        for (int j = 0; j < Target.Length; j++)
        {
            builder.Append(Convert.ToChar(Convert.ToInt32(Math.Floor(26 * random.NextDouble() + 65))));
        }

        **System.Threading.Thread.Sleep(20);**
        vector.Add(new GaStruct() { Fitness = 0, StrValue = builder.ToString().ToLower() });
        builder.Clear();
    }
}

everything is okay, all strings are random.

Community
  • 1
  • 1
Baranovskiy Dmitry
  • 463
  • 2
  • 5
  • 23
  • 5
    See http://stackoverflow.com/questions/4858790/random-not-that-random I ran into this myself. To get around it, declare the Random outside of the loop. – David Oct 22 '12 at 16:53
  • 2
    Also read http://csharpindepth.com/Articles/Chapter12/Random.aspx – Jon Skeet Oct 22 '12 at 16:55

0 Answers0