電腦生成四位數。玩家猜測,電腦回應:正確數字個數 B,位置也正確個數 C。給 N 次猜測記錄,推斷答案。唯一解輸出,否則 "Not sure"。
枚舉 1000~9999 每個數,驗證是否滿足所有記錄:
int judge(int x, int idx) {
// 分解 x 與 guess[idx] 為四位數組
// 統計位置相同數 cnt1,必須等於 C
// 雙重迴圈統計數字相同且未標記數 cnt2,必須等於 B
}
int main() {
while (scanf("%d",&n), n) {
// 讀入記錄
int cnt=0, ans;
for (int i=1000; i<=9999; i++) {
bool ok=true;
for (int j=1; j<=n; j++) if (!judge(i,j)) { ok=false; break; }
if (ok) { cnt++; ans=i; if (cnt==2) break; }
}
if (cnt==1) printf("%d\n", ans); else puts("Not sure");
}
}
9000 × 100 × 16 ≈ 1.4e7 操作,輕鬆過 2s。