fork download
  1. #include <stdio.h>
  2. #include <stdlib.h>
  3. #include <time.h>
  4. #include <string.h>
  5. #include <ctype.h>
  6. #include <stdbool.h>
  7.  
  8. void generateAnswer(int answer[]) {
  9. bool used[10] = {false};
  10. int count = 0;
  11. while (count < 4) {
  12. int digit = rand() % 10;
  13. if (!used[digit]) {
  14. used[digit] = true;
  15. answer[count++] = digit;
  16. }
  17. }
  18. }
  19.  
  20. bool isValidInput(char input[]) {
  21. if (strlen(input) != 4) return false;
  22.  
  23. bool used[10] = {false};
  24. for (int i = 0; i < 4; i++) {
  25. if (!isdigit(input[i])) return false;
  26. int digit = input[i] - '0';
  27. if (used[digit]) return false;
  28. used[digit] = true;
  29. }
  30. return true;
  31. }
  32.  
  33. bool getGuess(int guess[]) {
  34. char input[100];
  35.  
  36. if (scanf("%s", input) == EOF) {
  37. return false; // 輸入結束
  38. }
  39.  
  40. if (!isValidInput(input)) {
  41. return false; // 非法輸入
  42. }
  43.  
  44. for (int i = 0; i < 4; i++) {
  45. guess[i] = input[i] - '0';
  46. }
  47.  
  48. return true;
  49. }
  50.  
  51. void checkAB(int answer[], int guess[], int* A, int* B) {
  52. *A = 0;
  53. *B = 0;
  54.  
  55. for (int i = 0; i < 4; i++) {
  56. if (guess[i] == answer[i]) {
  57. (*A)++;
  58. } else {
  59. for (int j = 0; j < 4; j++) {
  60. if (guess[i] == answer[j] && i != j) {
  61. (*B)++;
  62. break;
  63. }
  64. }
  65. }
  66. }
  67. }
  68.  
  69. int main() {
  70. int answer[4], guess[4];
  71. int A = 0, B = 0;
  72. int attempts = 0;
  73.  
  74. srand(20240408); // 固定 seed,讓評測系統有一致答案
  75.  
  76. generateAnswer(answer);
  77.  
  78. while (A != 4) {
  79. if (!getGuess(guess)) {
  80. printf("輸入錯誤或輸入結束。\n");
  81. break;
  82. }
  83. checkAB(answer, guess, &A, &B);
  84. printf("%dA%dB\n", A, B);
  85. attempts++;
  86. }
  87.  
  88. if (A == 4) {
  89. printf("恭喜你猜對了!總共猜了 %d 次!\n", attempts);
  90. }
  91.  
  92. return 0;
  93. }
Success #stdin #stdout 0.01s 5288KB
stdin
1234
5678
9012
1230
4567
8456
stdout
0A1B
0A3B
0A0B
0A0B
0A3B
4A0B
恭喜你猜對了!總共猜了 6 次!