C#中比较生成代码数组与用户猜测数组的问题求助
搞定数组生成代码与用户猜测值的比较问题
嘿,我先把你给出的随机数字数组生成代码格式化一下,方便后续讨论:
Random r = new Random(); for (int i = 0; i < numbersArray.Length; i++) { numbersArray[i] = r.Next(1, digitRange); // digitRange代表最大数字值,比如不超过9 }
你没明确说比较时遇到的具体问题(比如是不知道怎么判断完全匹配?还是要区分数字对且位置对和数字对但位置错的情况?),我先针对猜数字类场景里最常见的两种需求给出解决方案:
1. 简单判断两个数组是否完全一致
如果只是要确认用户的猜测和生成的代码是不是完全一样,直接遍历每个索引逐一比对就行:
bool IsPerfectMatch(int[] codeArray, int[] guessArray) { // 先检查数组长度,不一样肯定不匹配 if (codeArray.Length != guessArray.Length) return false; for (int i = 0; i < codeArray.Length; i++) { if (codeArray[i] != guessArray[i]) return false; } return true; }
2. 精细化统计匹配情况(类似Mastermind游戏规则)
如果需要区分位置完全正确的数字和数字正确但位置不对的数量,就得稍微复杂一点,步骤大概是:先统计生成代码里每个数字的出现次数,先标记出位置匹配的,再统计剩下的数字里有多少是存在于代码中的:
(int correctSpot, int correctNumWrongSpot) CompareGuessToCode(int[] codeArray, int[] guessArray) { if (codeArray.Length != guessArray.Length) throw new ArgumentException("生成的代码数组和用户猜测数组长度必须一致哦"); int correctSpot = 0; // 用字典记录代码里每个数字还没被匹配的次数 Dictionary<int, int> codeDigitCounts = new Dictionary<int, int>(); // 第一步:先找位置完全匹配的,同时统计剩下的数字 for (int i = 0; i < codeArray.Length; i++) { if (codeArray[i] == guessArray[i]) { correctSpot++; } else { if (codeDigitCounts.ContainsKey(codeArray[i])) codeDigitCounts[codeArray[i]]++; else codeDigitCounts[codeArray[i]] = 1; } } // 第二步:统计数字对但位置错的数量 int correctNumWrongSpot = 0; for (int i = 0; i < guessArray.Length; i++) { if (codeArray[i] != guessArray[i]) // 跳过已经位置匹配的 { if (codeDigitCounts.TryGetValue(guessArray[i], out int count) && count > 0) { correctNumWrongSpot++; codeDigitCounts[guessArray[i]]--; } } } return (correctSpot, correctNumWrongSpot); }
调用的时候可以这样用:
// 假设numbersArray是你生成的代码数组,userGuess是用户输入的猜测数组 var matchResult = CompareGuessToCode(numbersArray, userGuess); Console.WriteLine($"位置正确:{matchResult.correctSpot} 个,数字对但位置错:{matchResult.correctNumWrongSpot} 个");
如果你的问题不是这两种情况(比如有报错、或者有特殊的比较规则),可以补充说明细节,我再帮你调整~
内容的提问来源于stack exchange,提问作者Ross
相关产品推荐
相关产品推荐

