首页 > 解决方案 > 收集猜4位数字游戏的正确数量

问题描述

如果我想知道错位的正确数字的数量,我想知道如何编码。例如,正确的是“7896”,但我输入了“8749”,所以我希望它显示它具有正确的“3”(789)。

void Run()
{

    // initialize the number of attempts
    int numberOfAttempts = 1000;

    Console.WriteLine("\nWelcome to Random Number Guessing Game.");
    Console.WriteLine("\n\nGuess the 4 digit random number XXXX.");
    Console.WriteLine("\nFor each digit, the number is chosen from 1 to 9  \nNumbers can repeat.");


    // Call the method to Generate the Random Number
    string randomNumber = GenerateRandomNumber();

    for (int i = 1; i <= numberOfAttempts; i++)
    {
        // Call the method to get the user input
        string userInput = GetUserInput(i);

        // Get the result - Collection containing the result of all 4 digits
        List<Result> result = GetResult(randomNumber, userInput);

        // Guess the count of number of digits that are correct
        int flagCount = result.Where(f => f.Flag == true).Count();

        // Get the place(s)/index of digits that are correct
        string digitsCorrect = string.Join(",", result.Where(f => f.Flag == true)
            .Select(c => (++c.Index).ToString()));


        // check the flag count and display appropriate message
        if (flagCount == 4)
        {                
            Console.WriteLine("Random Number:{0} , Your Input:{1}", randomNumber, userInput);
            Console.WriteLine("You guess is correct! Game Won..hurray...:)");
            break;
        }   
        else
        {

            digitsCorrect = flagCount == 0 ? "none" : digitsCorrect;
            Console.WriteLine(string.Format("Digit(s) in place {0} correct", digitsCorrect));
            Console.WriteLine(flagCount);

        }
    }

    Console.ReadLine();
}

我已经做了一些方法并且已经可以玩了

标签: c#.net

解决方案


像这样的东西?

  public static string Info(string guess, string actual)
    {
        int correctNumbers = 0;
        string correctChars = "";

        List<char> charlists = actual.ToList();
        foreach (var char_ in guess)
        {
            if (charlists.Contains(char_))
            {
                correctNumbers++;
                correctChars += char_.ToString();
                charlists.Remove(char_);     
            }
        }
        return $"{correctNumbers}({correctChars})";
    }

推荐阅读