解法1:
1 byte = 8 bit,因此可将一字节分为左右两部分进行计算,左边四位代表帅的位置(0000~0100),右边四位代表将的位置(0000~0100)。
书中代码:
#include "stdafx.h"
#include <iostream>
#define HALF_BITS_LENGTH 4
#define FULLMASK 255
#define LMASK (FULLMASK << HALF_BITS_LENGTH)
#define RMASK (FULLMASK >> HALF_BITS_LENGTH)
#define RSET(b,n) (b = ((LMASK & b) |(n)))
#define LSET(b,n) (b = ((RMASK & b) |((n) << HALF_BITS_LENGTH)))
#define RGET(b) (RMASK & b)
#define LGET(b) ((LMASK & b)>>HALF_BITS_LENGTH)
#define GRIDW 3
using namespace std;
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)
cout<<"A="<<LGET(b)<<",B="<<RGET(b)<<endl;;
return 0;
}
解法二:
由于将和帅各有9种走法, 因此共有9 * 9 = 81 种可能,因此设 i = 81.
其中各可能分别为:将=0时,帅=0~8;将=1时,帅=0~8;将=0时,帅=0~8;。。。将=8时,帅=0~8;
即: i = 0~8时, 将= i / 9 = 0,帅 = i % 9 = 0~8
i=9~17时, 将= i / 9 = 1,帅 = i % 9 = 0~8
...
i=72~80时, 将= i / 9 = 8,帅 = i % 9 = 0~8
书中代码:
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
unsigned char i = 81;
while(i--)
{
if(i/9%3 == i%9%3)
continue;
cout<<"A="<<i/9+1<<",B="<<i%9+1<<endl;
}
}