《Cracking the Coding Interview》——第17章:普通题——题目5

时间:2014-04-29 17:10:21   收藏:0   阅读:384

2014-04-28 22:44

题目:猜数字游戏。四个数字,每个都是0~9之间。你每猜一次,我都告诉你,有多少个位置和数字都对(全对),有多少个位置错数字对(半对)。比如“6309”,你猜“3701”,就有1全对,1半对。

解法:依照题意写就可以了。

代码:

bubuko.com,布布扣
 1 // 17.5 I am the Master Mind. Guess the number.
 2 // When you guessed the right number at the right position, you got a hit.
 3 // When you guessed the right number at the wrong position, you got a pseudo-hit.
 4 #include <cstdio>
 5 using namespace std;
 6 
 7 void check(int solution[], int guess[], int &hit, int &pseudo_hit)
 8 {
 9     static int c[4];
10     static int mark[4];
11     
12     int i;
13     for (i = 0; i < 4; ++i) {
14         c[i] = 0;
15         mark[i] = 0;
16     }
17     
18     hit = pseudo_hit = 0;
19     for (i = 0; i < 4; ++i) {
20         if (solution[i] == guess[i]) {
21             // hit
22             mark[i] = 1;
23             ++hit;
24         } else {
25             ++c[solution[i]];
26         }
27     }
28     for (i = 0; i < 4; ++i) {
29         if (mark[i]) {
30             continue;
31         }
32         // pseudo_hit
33         if (c[guess[i]] > 0) {
34             mark[i] = 2;
35             --c[guess[i]];
36             ++pseudo_hit;
37         }
38     }
39 }
40 
41 int main()
42 {
43     int solution[4];
44     int guess[4];
45     int hit, pseudo_hit;
46     int i;
47     
48     while (scanf("%d", &solution[0]) == 1) {
49         for (i = 1; i < 4; ++i) {
50             scanf("%d", &solution[i]);
51         }
52         for (i = 0; i < 4; ++i) {
53             scanf("%d", &guess[i]);
54         }
55         check(solution, guess, hit, pseudo_hit);
56         printf("%d hit(s), %d pseudo-hit(s).\n", hit, pseudo_hit);
57     }
58     
59     return 0;
60 }
bubuko.com,布布扣

 

《Cracking the Coding Interview》——第17章:普通题——题目5,布布扣,bubuko.com

评论(0
© 2014 mamicode.com 版权所有 京ICP备13008772号-2  联系我们:gaon5@hotmail.com
迷上了代码!