本文共 2830 字,大约阅读时间需要 9 分钟。
珠玑妙算游戏(Master Mind)的规则如下:计算机有4个槽,每个槽放一个球,颜色可能是红色(R)、黄色(Y)、绿色(G)或蓝色(B)。用户需要通过猜测颜色组合来猜出计算机的颜色设置。每个猜测中的每个槽位都有可能是正确的颜色(计为“猜中”)或仅颜色正确但槽位错误(计为“伪猜中”)。需要注意的是,“猜中”不能算入“伪猜中”。
给定一种颜色组合solution和一个猜测guess,编写一个方法,返回猜中和伪猜中的次数。例如,假设solution="RGBY",guess="GGRR",输出为 [1,1],其中猜中1次,伪猜中1次。
以下是实现该功能的Java代码:
import java.util.Arrays;public class Solution { public int[] masterMind(String solution, String guess) { int[] colorCounts = {0, 0, 0, 0}; // R, Y, G, B int[] solutionColorCounts = {0, 0, 0, 0}; // R, Y, G, B for (int i = 0; i < guess.length(); i++) { char c = guess.charAt(i); switch (c) { case 'R': colorCounts[0]++; break; case 'Y': colorCounts[1]++; break; case 'G': colorCounts[2]++; break; case 'B': colorCounts[3]++; break; } } for (int i = 0; i < solution.length(); i++) { char c = solution.charAt(i); switch (c) { case 'R': solutionColorCounts[0]++; break; case 'Y': solutionColorCounts[1]++; break; case 'G': solutionColorCounts[2]++; break; case 'B': solutionColorCounts[3]++; break; } } int[] result = new int[2]; for (int i = 0; i < guess.length(); i++) { for (int j = 0; j < solution.length(); j++) { if (guess.charAt(i) == solution.charAt(j) && i == j) { switch (solution.charAt(i)) { case 'R': solutionColorCounts[0]--; colorCounts[0]--; break; case 'Y': solutionColorCounts[1]--; colorCounts[1]--; break; case 'G': solutionColorCounts[2]--; colorCounts[2]--; break; case 'B': solutionColorCounts[3]--; colorCounts[3]--; break; } result[0]++; } } } result[1] = 0; if (colorCounts[0] > 0 && solutionColorCounts[0] > 0) { result[1] += Math.min(colorCounts[0], solutionColorCounts[0]); } if (colorCounts[1] > 0 && solutionColorCounts[1] > 0) { result[1] += Math.min(colorCounts[1], solutionColorCounts[1]); } if (colorCounts[2] > 0 && solutionColorCounts[2] > 0) { result[1] += Math.min(colorCounts[2], solutionColorCounts[2]); } if (colorCounts[3] > 0 && solutionColorCounts[3] > 0) { result[1] += Math.min(colorCounts[3], solutionColorCounts[3]); } return result; } public static void main(String[] args) { Solution sol = new Solution(); String solution = "YBBY", guess = "GYYB"; System.out.println(Arrays.toString(sol.masterMind(solution, guess))); }} 上述代码实现了一个高效的masterMind方法,用于计算猜中和伪猜中的次数。该方法通过统计每种颜色的出现次数,并逐一比较猜测和实际答案,最后计算出最终结果。
转载地址:http://rhniz.baihongyu.com/