《编程之美》读书笔记 -- 1.2中国象棋问题

解法1:

书中的意思是将一个byte的高4位与低4位分别保存帅和将的位置。

 1 // File Name: 1.2.cpp
 2 // Author: Missa_Chen
 3 // Created Time: 2013年07月06日 星期六 10时09分45秒
 4 
 5 #include <iostream>
 6 #include <string>
 7 #include <algorithm>
 8 #include <cstdio>
 9 #include <cstring>
10 #include <cmath>
11 #include <queue>
12 #include <map>
13 #include <stack>
14 #include <set>
15 #include <cstdlib>
16 #include <vector>
17 #include <time.h>
18 
19 using namespace std;
20 #define HALF_BITS_LENGTH 4
21 //记忆存储单元的一半
22 #define FULLMASK 255
23 // 1111 1111
24 #define LMASK (FULLMASK << HALF_BITS_LENGTH)
25 // 1111 0000
26 #define RMASK (FULLMASK >> HALF_BITS_LENGTH)
27 // 0000 1111
28 #define RSET(b, n) (b = ((LMASK & b) | (n)))
29 //将右边的值设为n
30 #define LSET(b, n) (b = ((RMASK & b) | ((n) << HALF_BITS_LENGTH)))
31 //将左边的值设为n
32 #define RGET(b) (RMASK & b)
33 //得到右边的值
34 #define LGET(b) ((LMASK & b) >> HALF_BITS_LENGTH)
35 //得到左边的值
36 #define GRIDW 3
37 
38 int main()
39 {
40     unsigned char b;
41     for (LSET(b, 1); LGET(b) <= GRIDW * GRIDW; LSET(b, (LGET(b) + 1))) 
42         for (RSET(b, 1); RGET(b) <= GRIDW * GRIDW; RSET(b, (RGET(b) + 1)))
43             if (LGET(b) % GRIDW != RGET(b) % GRIDW)
44                 printf("A = %d, B = %d\n", LGET(b), RGET(b));
45 
46     return 0;
47 }

解法2:解法2用到了一个变量来实现2重循环

原理在于 i = (i / 9 ) * 9 + i % 9.

显然很容易看出(i / 9)是外循环, (i % 9)是内循环。

扩展:

例如要实现一个三重循环:

for (int i = 0; i < 3; ++i)

  for (int j = 0; j < 4; ++j)

    for (int k = 0; k < 5; ++k)

      ......

则可以另 x = 3 * 4 * 5;

则 x / (4 *5) 为最外层循环, (x / 5)为中层。 x% 5为内层。

解法3 :

用到了一个没见过的结构体--位域(Bit Fields)。

这里有解释http://hi.baidu.com/xiao1dian/item/7cfa8e0e9d0e51cc905718ed

然后就知道怎么回事了。

posted @ 2013-07-06 10:44  Missa  阅读(297)  评论(0编辑  收藏  举报