Possible Duplicate:
Random number generator only generating one random number
I have a method in my work which generates a sentence by randomly choosing between a set of words as follows:
private string generateTest(string test)
{
test = test.ToLower();
string sentence = "";
for (int c = 0; c < 30; c++)
{
Random r = new Random();
int len = r.Next(3, 7);
string word = "";
for (int i = 0; i < len; i++)
{
word += test[r.Next(0, test.Length)];
}
sentence += word + ' ';
}
return sentence;
}
However, the problem is that after the first 6 words are generated randomly, all subsequent generations are exactly the same thing. e.g.
aqaaaz, qqzaq, aqqza, azqq, aazzq, aqqa, azzzq, azzzq, azzzq, azzzq,
azzzq, azzzq, azzzq, azzzq, azzzq, azzzq, azzzq, azzzq, azzzq, azzzq,
azzzq, azzzq, azzzq, azzzq, azzzq….
Then even when I restart the program, the same thing applies. I am thinking this is the .NET Runtime doing some automatic optimization. Can anyone explain better? How do I get around this problem?
You’re generating your instance for each cycle of the loop. Change your code to:
Also, you might want to assign it a meaningful seed. Right now, you’re not passing any to the constructor, which may yield results which are not really random if you recreate the same instance.
EDIT: As Shadow Wizard rightfully pointed out, giving it the same seed yields the same results. When I said “meaningful seed” I implied something that has random or pseudo-random attributes. There are many ways to produce more unpredictable results, but to solve your problem, moving the instance out of the cycle — Or instantiating it as a member of the containing class — is enough. Your choice for the seed or for your RNG should depend on your requirements.