c# - 收集猜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();
}
我已经做了一些方法并且已经可以玩了
解决方案
像这样的东西?
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})";
}
推荐阅读
- yaml - 用新值替换 yq 的 Yaml 值作为 bash 函数的输出,该函数接受当前值作为输入
- html - 使用纯 CSS 的从右到左、从上到下的砌体布局?
- reactjs - 如何更改按钮颜色 onClick Material-UI, React
- ios - 确定 UILabel 的字体大小或比例
- python - 导入我自己的 java 文件时找不到 Pyjnius 类
- google-schemas - 我们是否需要为每个环境请求 Gmail Schema 白名单请求?
- javascript - “获取”事件侦听器未在服务人员中触发以通过 Safari 中的 multipart/form-data 发布文件上传
- assembly - FAT16 Bootloader 仅加载文件的第一个簇
- powershell - IISRESET 和 ROBOCOPY 等某些命令在 Powershell v4 中已停止工作
- mysql - 从另一个表中的转换值更新表