Java – How to simplify these 4 loop functions into 1 function?

How to simplify these 4 loop functions into 1 function?… here is a solution to the problem.

How to simplify these 4 loop functions into 1 function?

I have an exercise. An int[8][8] chess grid. I have to find out if white can take away black.
The input is: (lowercase = black, uppercase = white).

tc.drf.t
ppp.pppp
... p... c
..... f..
.. C..P..
.. P.D.P.
PP..... P
T.F.RFCT

For qeen/towers, I used a loop to check each direction (top/bottom/left/right) and now there are 4 simple loop functions that look more or less the same.
I just want to have a feature but can’t find a way.
Any ideas?

    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;
    }

Solution

All four of your methods share three lines of code that can be extracted into a single method that you can call from the current method (which can be reduced to two lines of code if you reverse the comparison with attacked<). So basically there’s a separate method that does the following and calls it from your method:

char attacked = board[y].charAt(x);
if(attacked != '.') {
  return  Character.isLowerCase(attacked);
}

In addition, your methods are equal to each other in pairs: attackColTop() and attackRowLt are the same, as are the other two methods. If the only difference is the value of the parameter you pass to the method, you don’t need to have two methods that do the same thing: you can group the two methods together and then call it with the appropriate value.

Related Problems and Solutions