编程之美---中国象棋将帅问题

题目链接:http://www.msra.cn/Articles/ArticleItem.aspx?Guid=4c86d636-04bb-4ad9-b0bc-4c3496d18021#.

给出c++实现的简单代码:

#include <iostream>
#include <cstdio>
using namespace std;
const unsigned char fullmark=255; //11111111 
const unsigned char L_mask=fullmark<<4;//11110000
const unsigned char R_mask=fullmark>>4; //00001111
void RSET(unsigned char &b,int n)
{
	b=b&L_mask;
	b=b|n;
}
void LSET(unsigned char &b,int n)
{
	b=b&R_mask;
	b=b|(n<<4);
}
unsigned int rget(unsigned char b)//注意这里不能传引用 
{
	b=b&R_mask;
	return (unsigned int)b;
}
unsigned int lget(unsigned char b)//不能传引用 
{
	b=b&L_mask;
	b=b>>4;
	return (unsigned int)b;
}
int main()
{
	unsigned char b=0;
	LSET(b,1);
	//RSET(b,1);  //注意这里内存初始化不能放在外面 
	for(;lget(b)<=9;LSET(b,lget(b)+1))
		for(RSET(b,1);rget(b)<=9;RSET(b,rget(b)+1))
		{
			if(lget(b)%3!=rget(b)%3){
				cout<<"a=: "<<lget(b)<<", b=: "<<rget(b)<<endl;
			}
		} 
	return 0;	
}

这是传统的解法,下面的代码使用了位域的知识,比较简洁:

#include <iostream>
using namespace std;
struct node {
	unsigned char a:4;
	unsigned char b:4;
}i;
int main()
{
	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){
				cout<<"A=: "<<int(i.a)<<", B=: "<<int(i.b)<<endl;
			}
		}
	return 0;	
} 
    原文作者:xiaozhuaixifu
    原文地址: https://blog.csdn.net/xiaozhuaixifu/article/details/9260579
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞