所以我用 c# 制作了一个非常简单的单词生成器程序,效果相对较好。它根据用户定义的长度生成一个单词。
该算法为序列中的每个连续字母添加一个辅音,然后添加一个元音,这并不理想,但对于基本单词来说效果很好。
我唯一的问题是,如果“q”出现在它之前,我告诉它在字母序列中添加一个“u”,但无论我做了什么,它都会使单词至少有 1 个字母太长。
我在上面的评论中用星号标记了我的问题区域。这是代码:
public void WordFinder()
{
string word = null;
int cons;
int vow;
//counter
int i = 0;
bool isword = false;
Random rnd = new Random();
//set a new string array of consonants
string[] consonant = new string[]{"b","c","d","f","g","h","j","k","l","m","n","p","q","r","s","t","v","w","x","y","z"};
//set a new string array of vowels
string[] vowel = new string[]{"a","e","i","o","u"};
while (isword == false)
{
word = null;
Console.WriteLine("Pick the length of a word");
int num = Convert.ToInt32(Console.ReadLine());
//set the counter "i" to 1
i = 1;
if (num%2 == 0)
{
while (i <= num)
{
if (num != 1)
{
// current consonant = random consonant
cons = rnd.Next(0, 20);
// get the consonant from the string array "consonant" and add it to word
word = word + consonant[cons];
// add 1 to counter
i ++;
//* if the consonant is "q"
if (cons == 12)
{
// add "u" right after it
word = word + vowel[4];
// add 1 to counter
i++;
}
}
vow = rnd.Next(0, 4);
word = word + vowel[vow];
i ++;
}
}
if (num % 2 != 0)
{
while (i <= num - 1)
{
//repeat same code as done to even length
if (num != 1)
{
cons = rnd.Next(0, 20);
word = word + consonant[cons];
i ++;
if (cons == 12)
{
word = word + vowel[4];
i ++;
}
}
vow = rnd.Next(0, 4);
word = word + vowel[vow];
i ++;
}
// if the length is not equal to 1
if (num != 1)
{
// add a consonant to the end of the word
cons = rnd.Next(0, 20);
word = word + consonant[cons];
}
//if the length is 1
else if (num == 1)
{
// pick a vowel
vow = rnd.Next(0, 4);
word = word + vowel[vow];
}
}
i = 1;
Console.WriteLine(word);
Console.WriteLine("Is this a word? (y/n)");
string q = Console.ReadLine();
q = q.ToLower();
//if the answer is yes, then it is a word and end the loop
if (q == "y" || q == "yes")
{
isword = true;
}
//if the answer is no try the loop again
else if (q == "n" || q == "no")
{
isword = false;
}
}
}
// main method
static void Main(string[] args)
{
Program prog = new Program();
prog.WordFinder();
//wait for user input
Console.ReadLine();
}
}