Skip to content

Instantly share code, notes, and snippets.

@ivycheung1208
Created August 18, 2014 14:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ivycheung1208/4b244a3002bcbe5b844e to your computer and use it in GitHub Desktop.
Save ivycheung1208/4b244a3002bcbe5b844e to your computer and use it in GitHub Desktop.
CC150 17.5
/* 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