[英]How to simplify this 4 loop functions into 1 function?
我有一个练习。 一个 int[8][8] 国际象棋网格。 我必须找出白色是否可以带黑色。 输入是:(lowercaps = black,upper = white)
tc.drf.t
ppp.pppp
...p...c
.....f..
..C..P..
..P.D.P.
PP.....P
T.F.RFCT
对于皇后区/塔楼,我使用了一个循环来检查每个方向(上/下/左/右),现在有 4 个看起来或多或少相同的简单循环函数。 我只想拥有一个功能,但无法找到方法。 任何的想法?
static boolean attackRowRt(String[] board, int y, int fromX){
for(int x=fromX+1; x<=7; x++){
char attacked = board[y].charAt(x);
if(attacked == '.') continue;
return Character.isLowerCase(attacked);
}
return false;
}
static boolean attackRowLt(String[] board, int y, int fromX){
for(int x=fromX-1; x>=0; x--){
char attacked = board[y].charAt(x);
if(attacked == '.') continue;
return Character.isLowerCase(attacked);
}
return false;
}
static boolean attackColBtm(String[] board, int x, int fromY){
for(int y=fromY+1; y<=7; y++){
char attacked = board[y].charAt(x);
if(attacked == '.') continue;
return Character.isLowerCase(attacked);
}
return false;
}
static boolean attackColTop(String[] board, int x, int fromY){
for(int y=fromY-1; y>=0; y--){
char attacked = board[y].charAt(x);
if(attacked == '.') continue;
return Character.isLowerCase(attacked);
}
return false;
}
所有四种你的方法分享三行代码可以提取到一个单独的方法,你可以从当前的方法调用(并且可以将其简化为,如果你的两行代码反转比较有attacked
)。 所以基本上有一个单独的方法来执行以下操作并从您的方法中调用它:
char attacked = board[y].charAt(x);
if(attacked != '.') {
return Character.isLowerCase(attacked);
}
此外,您的方法成对地彼此相等: attackColTop()
和attackRowLt
是相同的,另外两个方法也是如此。 如果唯一的区别是传递给该方法的参数的值,则不需要有两个执行相同操作的方法:您可以将这两个方法包含在一个中,然后使用适当的值调用它。
每种方法的逻辑都是一样的,只是走的方向不同。 因此,通过将其作为参数传递,您可以对所有方向重复使用相同的方法:
static boolean attackLine(String[] board, int fromY, int fromX, int deltaX, int deltaY) {
int x = fromX + deltaX;
int y = fromY + deltaY;
while (true) {
if (x <0 || x > 7 || y <0 || y > 7) {
// outside board, this is the end
return false;
}
System.out.println(String.format("checking (x,y):(%d,%d)", x, y));
char attacked = board[y].charAt(x);
if (attacked != '.')
{
System.out.println(String.format("piece found at (x,y):(%d,%d)", x, y));
return Character.isLowerCase(attacked);
}
x += deltaX;
y += deltaY;
}
}
public static void main(String[] args) {
String[] board = new String[] { //
"tc.drf.t", //
"ppp.pppp", //
"...p...c", //
".....f..", //
"..C..P..", //
"..P.D.P.", //
"PP.....P", //
"T.F.RFCT" };
// white queen left up
System.out.println("" + attackLine(board, 7, 4, -1, -1));
// white queen right up
System.out.println("" + attackLine(board, 7, 4, 1, -1));
// white queen left down
System.out.println("" + attackLine(board, 7, 4, -1, 1));
// white queen right down
System.out.println("" + attackLine(board, 7, 4, 1, 1));
// white tower up
System.out.println("" + attackLine(board, 7, 0, 0, -1));
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.