首页 > 编程语言 >编程之美 - 1.2 中国象棋的将帅问题

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

时间:2022-10-31 12:07:34浏览次数:44  
标签:中国象棋 full return 1.2 int 之美 length edge half


问题导读:


在一把象棋的残局中,象棋双方的将帅不可以相见,即不可以在中间没有其他棋子的情况下在同一列出现。而将、帅各被限制在己方的3*3的格子中运动。相信大家都非常熟悉象棋的玩法吧,这里就不详细说明游戏规则了。
用A、B代表将和帅,请写出一个程序,输出A、B所有合法的位置。要求在代码中只能用一个变量。


解决方案:


注:我这里处理 4*4 的两个矩阵


1. 

package Chapter1;

public class Func_1_2_1 {

// int的bit大小的一半
int half_bits_length;
// 32个1
int full_mask;
// 边长
double edge;
// 周长
double girth;

public Func_1_2_1(int half_bits_length, int full_mask, double edge) {
this.half_bits_length = half_bits_length;
this.full_mask = full_mask;
this.edge = edge;
this.girth = Math.pow(edge, 2);
}
/*
规则:
& 0 -> 0
& 1 -> 本身
| 0 -> 本身
总结:
1.1 l &0&1 再|(<<)
1.2 r &1&0 再|
2.1 l &1&0 再移位
2.2 r &0&1
*/
// 返回01
int lMask() {
return this.full_mask >> this.half_bits_length;
}
// 返回10
int rMask() {
return this.full_mask << this.half_bits_length;
}
// 将i的左边赋值为n
int lSet(int i, int n) {
return ((i & lMask()) | (n << this.half_bits_length));
}
// 将i的右边赋值为n
int rSet(int i, int n) {
return ((i & rMask()) | n);
}
// 得到i的左侧的值
int lGet(int i) {
return (i & rMask()) >> this.half_bits_length;
}
// 得到i的右侧的值
int rGet(int i) {
return (i & lMask());
}

public static void main(String []args) {
Func_1_2_1 f = new Func_1_2_1(Integer.SIZE/2, Integer.MAX_VALUE, 4);
int i = 0;
for(i = f.lSet(i, 1); f.lGet(i) <= f.girth; i = f.lSet(i, (f.lGet(i) + 1))) {
for(i = f.rSet(i, 1); f.rGet(i) <= f.girth; i = f.rSet(i, (f.rGet(i) + 1))) {
if(f.lGet(i) % f.edge == f.rGet(i) % f.edge) {
System.out.println("A = " + f.lGet(i) + " B = " + f.rGet(i));
}
}
}
}
}


2.

package Chapter1;

public class Func_1_2_2 {
public static void main(String []args) {
int i = 256;
while (i-- != 0) {
/*
for i in 16:
for j in 16:
if i%4 == j%4:
continue
print(i,j)
*/
if(i/16%4 == i%16%4)
continue;
System.out.println("A = " + i/16 + " B = " + i%16);
}
}
}




标签:中国象棋,full,return,1.2,int,之美,length,edge,half
From: https://blog.51cto.com/u_11290086/5808980

相关文章