# 编程之美读书笔记1.2——中国象棋将帅问题

2017-08-14 10:08:29来源:oschina作者:AllenOR灵感人点击

http://blog.csdn.net/pipisorry/article/details/36380669

/****************************************************************************/
/* 1.2中国象棋将帅问题 皮皮 2014-7-1 */
/****************************************************************************/
#include
typedef struct bitField{
unsigned char a:4;
unsigned char b:4;
}bit;void chessTest1(){
char column = 1;
for(; column <=3 ; column ++){ //A的列选
for(; column <= 9; column += 3){ //A（和B）的行选
printf("A = %d, B = %d/n", column, column%3 + 1);
printf("A = %d, B = %d/n", column, column%3 + 1 + 3);
printf("A = %d, B = %d/n", column, column%3 + 1 + 6);
printf("A = %d, B = %d/n", column, (column + 1)%3 + 1);
printf("A = %d, B = %d/n", column, (column + 1)%3 + 1 + 3);
printf("A = %d, B = %d/n", column, (column + 1)%3 + 1 + 6);
}
column -= 9;
}
}
void chessTest2(){
char i = 81;
while(i--){
if(i/9 % 3 == i % 9 %3) //i/9(A的编号-1[0~8]) % 3(A的列); i%9(B的编号-1[8~0]) %3
continue; //同列则continue
printf("A = %d, B = %d/n",i/9 + 1, i%9 + 1);
}
}
void chessTest3(){
bit i;
for(i.a = 1; i.a <= 9; i.a++)
for(i.b = 1; i.b <= 9; i.b ++)
if(i.a%3 != i.b%3) //A B不同列
printf("A = %d, B = %d/n", i.a, i.b);
}
void main(){ chessTest3();}

1.看chessTest1，其实只需要printf就可以输出正解，只要AB不同列就可以，共3*3 * 2*3 = 54种情况

2.chessTest2比较不好想，只要注意AB编号不能同时相同（if判断语句中）且AB不同列时才输出就可以

3.chessTest3使用了位域方法，位域知识参见：http://blog.csdn.net/pipisorry/article/details/36220851

//外层循环变量b使用i的第4-7位，初始值为1，最大值为8。
//内层循环变量a使用i的第0-3位，初始值为b+1，最大值为9。
for (unsigned i = 0x10; i < 0x90; i += 0x10)
for (i= (i & 0xF0) | (i >> 4); (++i & 0xF) < 10; )
if (((i & 0xF) - (i >> 4)) != 3 && ((i & 0xF) - (i >> 4)) != 6)
std::cout << "A=" << (i >> 4)<< ", B="<< (i & 0xF) << "/n"
<< "A=" << (i & 0xF) << ", B="<< (i >> 4)<< "/n";
from:
http://blog.csdn.net/pipisorry/article/details/36380669
ref:http://www.cnblogs.com/flyinghearts/archive/2010/09/08/1821042.html