#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>
#include <ctype.h>
#include <stdbool.h>

void generateAnswer(int answer[]) {
    bool used[10] = {false};
    int count = 0;
    while (count < 4) {
        int digit = rand() % 10;
        if (!used[digit]) {
            used[digit] = true;
            answer[count++] = digit;
        }
    }
}

bool isValidInput(char input[]) {
    if (strlen(input) != 4) return false;

    bool used[10] = {false};
    for (int i = 0; i < 4; i++) {
        if (!isdigit(input[i])) return false;
        int digit = input[i] - '0';
        if (used[digit]) return false;
        used[digit] = true;
    }
    return true;
}

bool getGuess(int guess[]) {
    char input[100];

    if (scanf("%s", input) == EOF) {
        return false; // 輸入結束
    }

    if (!isValidInput(input)) {
        return false; // 非法輸入
    }

    for (int i = 0; i < 4; i++) {
        guess[i] = input[i] - '0';
    }

    return true;
}

void checkAB(int answer[], int guess[], int* A, int* B) {
    *A = 0;
    *B = 0;

    for (int i = 0; i < 4; i++) {
        if (guess[i] == answer[i]) {
            (*A)++;
        } else {
            for (int j = 0; j < 4; j++) {
                if (guess[i] == answer[j] && i != j) {
                    (*B)++;
                    break;
                }
            }
        }
    }
}

int main() {
    int answer[4], guess[4];
    int A = 0, B = 0;
    int attempts = 0;

    srand(20240408); // 固定 seed，讓評測系統有一致答案

    generateAnswer(answer);

    while (A != 4) {
        if (!getGuess(guess)) {
            printf("輸入錯誤或輸入結束。\n");
            break;
        }
        checkAB(answer, guess, &A, &B);
        printf("%dA%dB\n", A, B);
        attempts++;
    }

    if (A == 4) {
        printf("恭喜你猜對了！總共猜了 %d 次！\n", attempts);
    }

    return 0;
}