您的位置:首页 > 编程语言

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

2013-07-06 10:44 399 查看
解法1:

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

// File Name: 1.2.cpp
// Author: Missa_Chen
// Created Time: 2013年07月06日 星期六 10时09分45秒

#include <iostream>
#include <string>
#include <algorithm>
#include <cstdio>
#include <cstring>
#include <cmath>
#include <queue>
#include <map>
#include <stack>
#include <set>
#include <cstdlib>
#include <vector>
#include <time.h>

using namespace std;
#define HALF_BITS_LENGTH 4
//记忆存储单元的一半
#define FULLMASK 255
// 1111 1111
#define LMASK (FULLMASK << HALF_BITS_LENGTH)
// 1111 0000
#define RMASK (FULLMASK >> HALF_BITS_LENGTH)
// 0000 1111
#define RSET(b, n) (b = ((LMASK & b) | (n)))
//将右边的值设为n
#define LSET(b, n) (b = ((RMASK & b) | ((n) << HALF_BITS_LENGTH)))
//将左边的值设为n
#define RGET(b) (RMASK & b)
//得到右边的值
#define LGET(b) ((LMASK & b) >> HALF_BITS_LENGTH)
//得到左边的值
#define GRIDW 3

int main()
{
unsigned char b;
for (LSET(b, 1); LGET(b) <= GRIDW * GRIDW; LSET(b, (LGET(b) + 1)))
for (RSET(b, 1); RGET(b) <= GRIDW * GRIDW; RSET(b, (RGET(b) + 1)))
if (LGET(b) % GRIDW != RGET(b) % GRIDW)
printf("A = %d, B = %d\n", LGET(b), RGET(b));

return 0;
}


解法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

然后就知道怎么回事了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: