如果我想知道正确数字的数量,即使它们错位排列,我该如何编码?例如,正确的数字是"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();
}
我已经完成了一些方法,现在可以进行游戏了。
GetResult
方法是做什么的?Result
对象长什么样子?代码中缺少重要信息。 - ADyson