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.