题目
原文:
The Game of Master Mind is played as follows:
The computer has four slots containing balls that are red (R ), yellow (Y), green (G) or blue (B). For example, the computer might have RGGB (e.g., Slot #1 is red, Slots #2 and #3 are green, Slot #4 is blue).
You, the user, are trying to guess the solution. You might, for example, guess YRGB.When you guess the correct color for the correct slot, you get a “hit”. If you guess a color that exists but is in the wrong slot, you get a “pseudo-hit”. For example, the guess YRGB has 2 hits and one pseudo hit.
For each guess, you are told the number of hits and pseudo-hits. Write a method that, given a guess and a solution, returns the number of hits and pseudo hits.
译文:这游戏Master Mind的游戏规则如下:
计算机程序提供四个槽,可以容纳红R、黄Y、绿G、蓝B的球,例如,当有RGGB,(eg:槽1是红,槽2和3是绿,槽4是蓝)
使用者试着猜出这个排列,例如,你可能猜YRGB,当你猜对颜色和位置时,你得到一个“hit”,如果你猜到一个存在的颜色,但槽的位置不匹配,你得到一个“pseudo-hit”,例如你猜YRGB得到2个hits和一个pseudo-hit
对于每猜一次,你被告知获得的hits和pseudo-hit的数量,写一个方法猜出这个排列,返回这个hits和pseudo-hit的数量。
解答
首先要理解并明确题意,对于pseudo-hit的定义,猜对颜色但位置不对的,得到一个pseudo-hit,但包不包括某个位置和颜色都匹配的情况下,但又和领一位置同颜色?(如:原颜色:RGGB,猜测:YRGB的G与原颜色的第一个G算不算一个pseudo-hit?题目是不算的,但书本给出的答案却算)或者多个同颜色的对应一个,又怎样算?(如:原颜色:GYRB,猜测:YGGG),我是这样理解的,若某一种颜色在某位置已经对应得到hits,就不会再得到pseudo-hit,猜测的颜色可以一个对应多个(只要不得到hits),也可以多个对应一个(多个)。
代码如下:
class Q19_5{ public static int hits=0; public static int perudohits=0; public static void main(String[] args){ guessHit("RGGB","YRGB"); System.out.println("hits="+hits+",perudohits="+perudohits); Result res=guessHit2("RGGB","YRGB"); System.out.println("hits="+res.hits+",perudohits="+res.perudohits); } public static void guessHit(String trueStr,String guessStr){ int[] mark=new int[4]; for(int i=0;i<guessStr.length();i++){ mark[i]=0; if(guessStr.charAt(i)==trueStr.charAt(i)){ hits++; mark[i]=1; } for(int j=0;j<trueStr.length();j++){ if(guessStr.charAt(i)==trueStr.charAt(j)&&i!=j&&mark[i]!=1) perudohits++; } } } //method 2 (ctci) static class Result{ public int hits; public int perudohits; } public static Result guessHit2(String guess,String solution){ Result res=new Result(); int solution_mask=0; for(int i=0;i<4;++i){ solution_mask|=1<<(1+solution.charAt(i)-'A'); } for(int i=0;i<4;++i){ if(guess.charAt(i)==solution.charAt(i)){ ++res.hits; }else if((solution_mask&(1<<(1+guess.charAt(i)-'A')))>=1){ ++res.perudohits; } } return res; } }
---EOF---