【问题标题】:Random Word Generator #2随机词生成器#2
【发布时间】:2013-08-07 17:48:03
【问题描述】:

所以我用 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();
}
}

【问题讨论】:

  • 该代码中的几乎所有 cmets 都没有帮助。注释应该在那里告诉您代码没有告诉您的信息(或者从代码中不明显)。仅说明代码的确切功能的评论对任何人都没有帮助,只会浪费人们的时间。
  • 我不明白 它使单词成为字母(或者在“u”之后添加“q”的次数变长是什么意思。你可能尝试使用 consonant[cons] == 'q' 作为您的 if 条件,而不是您那里的幻数 12。
  • 我正在阅读此内容的方式,每次通过循环,您都添加 2 个字母。一个辅音和一个元音。在生成 Q 的情况下,您总共添加了 3 个字母:QU 加上一个随机的其他元音。这里的逻辑似乎离题了。
  • @OrrenRavid:你不必为你的 cmets 道歉。那是建设性的批评,而不是陈旧的批评。 @servy 只是注意到你在用像 i++; // add one to i 这样的 cmets 来浪费你的时间。把你的 cmets 留给那些难以理解的东西,这样你就可以节省时间和精力。哪个好!
  • @Will 您是否还会在此类 cmets 上浪费读者的时间,冒着随着代码更改而导致 cmets 不同步的风险(这意味着它要么是错误的,因此令人困惑,要么是更新所有内容的维护成本) cmets),也使得找到真正有意义的 cmets 变得更加困难。如果你强迫读者因为它们是绒毛而忽略所有的 cmets,他们也会跳过他们真正需要阅读的重要内容。

标签: c#


【解决方案1】:

我重构了你的答案,经过一些调试,我让它工作了。抱歉,我不能只是对其进行调整来修复它。我相信它不允许单词以“qu”或“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)];
}

编辑:但是,这仍然很不守规矩。生成一个随机字符串,完成后将“q”替换为“qu”怎么样?

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)];
}

【讨论】:

  • 感谢 Greg 的这些回答。我对 c# 和一般编程比较陌生,并且一直在玩 c#,我想出了这段代码。由于我对 c# 库和类的了解很少,我不得不以如此粗暴和简单的方式编写代码。感谢您展示了这两种选择,一种更接近源程序,另一种更有效。
【解决方案2】:

由于您构建循环的方式,您的问题正在发生。

您使用两个单独的循环,具体取决于长度是偶数还是奇数,并假设每个循环将添加两个字符。但是,当遇到 Q 时,循环会添加 3 个字符,这会导致循环多执行一次,而您最终会得到一个额外的字符。

试试这个方法:

    string GenerateWord(int length)
    {
        if (length < 1) // do not allow words of zero length
            throw new ArgumentException("Length must be greater than 0");

        string word = string.Empty;

        if (rand.Next() % 2 == 0) // randomly choose a vowel or consonant to start the word
            word += cons[rand.Next(0, 20)];
        else
            word += vowel[rand.Next(0, 4)];

        for (int i = 1; i < length; i += 2) // the counter starts at 1 to account for the initial letter
        { // and increments by two since we append two characters per pass
            char c = cons[rand.Next(0, 20)];
            char v = vowel[rand.Next(0, 4)];

            if (c == 'q') // append qu if the random consonant is a q
                word += "qu";
            else // otherwise just append a random consant and vowel
                word += c + v;
        }

        // the word may be short a letter because of the way the for loop above is constructed
        if (word.Length < length) // we'll just append a random consonant if that's the case
            word += cons[rand.Next(0, 20)];

        return word;
    }

【讨论】:

  • 良好的第一次通过,但它跳过了元音始终跟随QU 的要求。此外,还有可能以 Q 结尾。
  • 我没有看到该要求已定义。我看到 OPs 代码暗示了它,但我不完全确定这是故意的。
  • @Michael - 我有一个答案that I deleted OP 提出了这个要求。很抱歉造成混乱。
【解决方案3】:

我做了一个较小的,因为我受到这篇文章的启发。 我是 C# 的新手

{
    class MainClass
    {
        public static void Main(string[] args)
        {
            string[] consonants = new string[] { "b", "c", "d", "f", "g", "h", "j", "k", "l", "m", "n", "p", "q", "r", "s", "t", "v", "w", "x", "z" };
            string[] vowels = new string[] { "a", "e", "i", "o", "u", "y", "ee", "aa","ij", "oe" };

            while (true)
            {
                Console.WriteLine("");
                Console.WriteLine("");
                Console.WriteLine("");
                Console.Write("Length word: ");
                int Length = Convert.ToInt32(Console.ReadLine());

                Random rnd = new Random();
                int a;
                int goal = Length;

                for (int i = 0; i != goal; i++)
                {
                    a = rnd.Next(1, consonants.Length);
                    if (i % 2 == 0)
                    {
                        a = rnd.Next(1, consonants.Length);
                        Console.Write(consonants[a]);
                    }
                    Thread.Sleep(10);
                    if (i % 2 != 0)
                    {
                        a = rnd.Next(1, vowels.Length);
                        Console.Write(vowels[a]);
                    }
                    Thread.Sleep(200);
                }
            }
        }
    }
}

【讨论】:

    猜你喜欢
    • 2017-09-03
    • 2013-09-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多