Game of master mind

The Game of Master Mind is played as follows:

The computer has four slots, and each slot will contain a ball that is red(R), yellow(Y), green(G) or blue(B). For example, the computer might have RGGB(slot# 1 is red, Slots#2 and #4 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.” Note that a slot that is a hit can never count as a pseudo-hit.

For example, if the actual solution is RGBY and you guess GGRR, you have one hit and one pseudo-hit.

Write a method that, given a guess and a solution, returns the number of hits and pseudo-hits.

01 void colorCount(char a, int A[4])
02 {
03     switch(a){
04         case ‘R’:
05             A[0]++;
06             break;
07         case ‘Y’:
08             A[1]++;
09             break;
10         case ‘G’:
11             A[2]++;
12             break;
13         case ‘B’:
14             A[3]++;
15             break;
16     }
17 }
19 void mindHit(string a, string b, int& num_hit, int& pseudo_hit)
20 {
21     int A[4];
22     int B[4];
23     for(int i=0;i<4;i++)
24         A[i]=B[i]=0;
25     num_hit=pseudo_hit=0;
26     for(int i=0;i<4;i++){
27         if(a[i]==b[i]){
28             num_hit++;
29             continue;
30         }
31         colorCount(a[i],A);
32         colorCount(b[i],B);
33     }
34     for(int i=0;i<4;i++){
35         pseudo_hit+=min(A[i],B[i]);
36     }
37 }
This entry was posted in String. Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s