Someone has written another version in another forum, I think it's better than mine, simple and efficient
Code:
#include <stdio.h>
int main()
{
int answer = 0;
int guess;
int black = 0;
int white = 0;
int round = 1;
int a1, a2, a3, a4;
int g1, g2, g3, g4;
int i;
srand(time(NULL));
for (i = 0; i < DIGIT_COUNT; ++i) {
answer *= 10;
answer += rand() % DIGIT_LENGTH + MIN_DIGIT;
}
printf("The answer is %d\n", answer);
for (round = 1; black != DIGIT_COUNT && round <= MAX_ROUND; ++round) {
int workAnswer;
int workGuess;
int validInput;
do {
printf("Round %2d: Your guess (-1 to quit): ", round);
validInput = scanf("%d", &guess);
if (validInput == 0) {
fflush(stdin);
puts("Invalid input. Please enter again.");
}
} while (!validInput);
if (guess == -1)
break;
a1 = a2 = a3 = a4 = 0;
g1 = g2 = g3 = g4 = 0;
black = 0;
workAnswer = answer;
workGuess = guess;
if (workAnswer % 10 == workGuess % 10) {
++black;
a1 = g1 = 1;
}
workAnswer /= 10;
workGuess /= 10;
if (workAnswer % 10 == workGuess % 10) {
++black;
a2 = g2 = 1;
}
workAnswer /= 10;
workGuess /= 10;
if (workAnswer % 10 == workGuess % 10) {
++black;
a3 = g3 = 1;
}
workAnswer /= 10;
workGuess /= 10;
if (workAnswer % 10 == workGuess % 10) {
++black;
a4 = g4 = 1;
}
white = 0;
workGuess = guess;
if (g1 == 0) {
int done = 0;
workAnswer = answer;
if (!done && workAnswer % 10 == workGuess % 10 && a2 == 0) {
++white;
a2 = 1;
done = 1;
}
workAnswer /= 10;
if (!done && workAnswer % 10 == workGuess % 10 && a3 == 0) {
++white;
a3 = 1;
done = 1;
}
workAnswer /= 10;
if (!done && workAnswer % 10 == workGuess % 10 && a4 == 0) {
++white;
a4 = 1;
done = 1;
}
}
workGuess /= 10;
if (g2 == 0) {
int done = 0;
workAnswer = answer;
if (!done && workAnswer % 10 == workGuess % 10 && a1 == 0) {
++white;
a1 = 1;
done = 1;
}
workAnswer /= 10;
workAnswer /= 10; /* skip digit 2 */
if (!done && workAnswer % 10 == workGuess % 10 && a3 == 0) {
++white;
a3 = 1;
done = 1;
}
workAnswer /= 10;
if (!done && workAnswer % 10 == workGuess % 10 && a4 == 0) {
++white;
a4 = 1;
done = 1;
}
}
workGuess /= 10;
if (g3 == 0) {
int done = 0;
workAnswer = answer;
if (!done && workAnswer % 10 == workGuess % 10 && a1 == 0) {
++white;
a1 = 1;
done = 1;
}
workAnswer /= 10;
if (!done && workAnswer % 10 == workGuess % 10 && a2 == 0) {
++white;
a2 = 1;
done = 1;
}
workAnswer /= 10;
workAnswer /= 10; /* skip digit 3 */
if (!done && workAnswer % 10 == workGuess % 10 && a4 == 0) {
++white;
a4 = 1;
done = 1;
}
}
workGuess /= 10;
if (g4 == 0) {
int done = 0;
workAnswer = answer;
if (!done && workAnswer % 10 == workGuess % 10 && a1 == 0) {
++white;
a1 = 1;
done = 1;
}
workAnswer /= 10;
if (!done && workAnswer % 10 == workGuess % 10 && a2 == 0) {
++white;
a2 = 1;
done = 1;
}
workAnswer /= 10;
if (!done && workAnswer % 10 == workGuess % 10 && a3 == 0) {
++white;
a3 = 1;
done = 1;
}
no need to check digit
}
printf("Black: %d White: %d\n", black, white);
}
printf("The answer is %d\n", answer);
return 0;
}