Random Word Generator #2
I refactored your answer and after some debugging I got it to work. Sorry I couldn't just do a tweak on it to fix it. I believe it does not allow a word to end in "qu" or "q".
public void WordFinder()
{
bool isWord = false;
Random rnd = new Random();
string[] consonants = { "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z" };
string[] vowels = { "a", "e", "i", "o", "u" };
while (isWord == false)
{
string word = "";
Console.WriteLine("Pick the length of a word");
int requestedLength = Convert.ToInt32(Console.ReadLine());
// Generate the word in consonant / vowel pairs
while (word.Length < requestedLength)
{
if (requestedLength != 1)
{
// Add the consonant
string consonant = GetRandomLetter(rnd, consonants);
if (consonant == "q" && word.Length + 3 <= requestedLength) // check +3 because we'd add 3 characters in this case, the "qu" and the vowel. Change 3 to 2 to allow words that end in "qu"
{
word += "qu";
}
else
{
while( consonant == "q")
{
// Replace an orphaned "q"
consonant = GetRandomLetter(rnd, consonants);
}
if (word.Length + 1 <= requestedLength)
{
// Only add a consonant if there's enough room remaining
word += consonant;
}
}
}
if (word.Length + 1 <= requestedLength)
{
// Only add a vowel if there's enough room remaining
word += GetRandomLetter(rnd, vowels);
}
}
Console.WriteLine(word);
Console.WriteLine("Is this a word? (y/n)");
string q = Console.ReadLine().ToLower();
if (q == "y" || q == "yes")
{
isWord = true;
}
}
}
private static string GetRandomLetter(Random rnd, string[] letters)
{
return letters[rnd.Next(0, letters.Length - 1)];
}
Edit: However, that's still pretty unruly. How about generating a random string, and then replacing "q" with "qu" after you're done?
public string WordFinder2(int requestedLength)
{
Random rnd = new Random();
string[] consonants = { "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "y", "z" };
string[] vowels = { "a", "e", "i", "o", "u" };
string word = "";
if (requestedLength == 1)
{
word = GetRandomLetter(rnd, vowels);
}
else
{
for (int i = 0; i < requestedLength; i+=2)
{
word += GetRandomLetter(rnd, consonants) + GetRandomLetter(rnd, vowels);
}
word = word.Replace("q", "qu").Substring(0, requestedLength); // We may generate a string longer than requested length, but it doesn't matter if cut off the excess.
}
return word;
}
private static string GetRandomLetter(Random rnd, string[] letters)
{
return letters[rnd.Next(0, letters.Length - 1)];
}