I have two methods, generateNounPhrase() and generateVerbPhrase(). VerbPhrase will call on NounPhrase half the time and it's output the output should be something to the effect of:
the empty lot re-animates this pyramid
(bold indicating where generateNounPhrase() is logically called). The true output however is in the form of:
the empty lot re-animates the empty lot
At first I thought my randomIndex method wasn't working as I had intended, but if I run the two methods again I do get different noun phrases but they are not unique at the beginning and end of the sentence as they should be.
Any idea what I am doing wrong in order to get one method to show the same result?
private string generateNounPhrase()
{
string nounPhraseString = "";
nounPhraseString = nounMarkersStringList[randomIndex(0,nounMarkersStringList.Count-1)];
if (included(1, 4, 2) == true)
{
nounPhraseString += " " + adjectivesStringList[randomIndex(0, adjectivesStringList.Count - 1)];
}
nounPhraseString += " " + nounsStringList[randomIndex(0, nounsStringList.Count - 1)];
return nounPhraseString;
}
private string generateVerbPhrase()
{
string verbPhraseString = "";
if (included(1, 4, 2) == true)
{
开发者_高级运维 verbPhraseString = intransitiveVerbsStringList[randomIndex(0, intransitiveVerbsStringList.Count - 1)];
}
else
{
verbPhraseString = transitiveVerbsStringList[randomIndex(0, transitiveVerbsStringList.Count - 1)] + " " + generateNounPhrase();
}
return verbPhraseString;
}
Without seeing the code for randomIndex, I can't be certain, but it seems like you are probably creating a new instance of the Random class each time you call randomIndex. If you do this twice in a very short time, as you would be here, it will seed the random number generator with the same value both times (because it is seeded with the current time) and you will get the same 'random' number returned both times.
Instead, you should use a single instance of Random for all randomIndex calls.
I highly suspect your randomIndex method does something to the following effect:
Random r = new Random();
return r.Next (0, max);
The problem with the above code is that when you run it at different time, it returns a different value. But if you run it like the following, it almost always returns the same value:
Console.WriteLine ("{0} == {1}?", randomIndex(0,10), randomIndex(0,10));
This is because the randomizer uses the current time as its seed. 2 randomizer created at the same time, will always return the same value. The right way to do it would be:
class MyRand // Assuming MyRand is the class name
{
private Random r = new Random();
public int GetRand(int min, int max)
{
return r.Next(min, max);
}
}
Alternatively, you can make the members static.
精彩评论