Created
August 18, 2014 14:53
-
-
Save ivycheung1208/4b244a3002bcbe5b844e to your computer and use it in GitHub Desktop.
CC150 17.5
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* CC150 17.5 */ | |
// the game of master mind (RGBY) | |
#include <iostream> | |
#define N 4 | |
class Result { | |
public: | |
Result() : hits(0), phits(0) {} | |
Result(int h, int p) : hits(h), phits(p) {} | |
int hits; | |
int phits; | |
}; | |
int colormap(char color) { // translate color to index | |
switch (color) { | |
case 'R': | |
return 0; | |
case 'G': | |
return 1; | |
case 'B': | |
return 2; | |
case 'Y': | |
return 3; | |
default: | |
return -1; // indicate invalid entry | |
} | |
} | |
Result guessResult(char sol[], char guess[]) | |
{ | |
int hits = 0, phits = 0; | |
int solCount[N] = { 0, 0, 0, 0 }; | |
int guessCount[N] = { 0, 0, 0, 0 }; | |
for (int i = 0; i != N; ++i) { // count hits and occurrence of non-hits | |
if (sol[i] == guess[i]) | |
++hits; | |
else { | |
++solCount[colormap(sol[i])]; | |
++guessCount[colormap(guess[i])]; | |
} | |
} | |
for (int i = 0; i != N; ++i) | |
phits += solCount[i] < guessCount[i] ? solCount[i] : guessCount[i]; | |
return Result(hits, phits); | |
} | |
bool readGuess(char guess[]) | |
{ | |
bool valid = true; | |
for (int i = 0; i != N; ++i) { | |
std::cin >> guess[i]; | |
if (colormap(guess[i]) == -1) { | |
std::cerr << "Invalid input!" << std::endl; | |
valid = false; // keep read cin rather than break; otherwise need to clear cin buffer | |
} | |
} | |
return valid; | |
} | |
int main() | |
{ | |
char sol[N]; | |
std::cout << "Solution: "; | |
while (!readGuess(sol)); // store solution | |
char guess[N]; | |
while (1) { | |
std::cout << "Guess: "; | |
while (!readGuess(guess)); // read guess | |
Result result = guessResult(sol, guess); | |
std::cout << "Hits: " << result.hits << "; "; | |
std::cout << "Pseudo-hits: " << result.phits << std::endl; | |
if (result.hits == N) | |
break; | |
} | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment