Game of life: find neighbors

I am making a game "Life" and I made this method to find neighboring neighbors.

private int getNeighbours(LifeBoard board, int row, int col){
    if(board.get(row+1, col)){
        neighbours++;
    }
    if(board.get(row-1, col)){
        neighbours++;
    }
    if(board.get(row, col+1)){
        neighbours++;
    }
    if(board.get(row, col-1)){
        neighbours++;
    }
    if(board.get(row+1, col+1)){
        neighbours++;
    }
    if(board.get(row-1, col-1)){
        neighbours++;
    }
    if(board.get(row+1, col-1)){
        neighbours++;
    }
    if(board.get(row-1, col+1)){
        neighbours++;
    }

    return neighbours;
}

      

It seems to me like it's horribly coded and shriveled up, so my question is: .. Is there a better way to do this? Right now, this "sorting" works, but I think if I could do it with a loop.

Thank.

+3


source to share


1 answer


Well, you can use for loops and just explicitly exclude the location itself (i.e. when the x and y offsets are 0):

private int getNeighbours(LifeBoard board, int row, int col) {
    int neighbours = 0;
    for (int xOffset = -1; xOffset < 2; xOffset++) {
        for (int yOffset = -1; yOffset < 2; yOffset++) {
            if ((xOffset != 0 || yOffset != 0)
                  && board.get(row + yOffset, col + xOffset)) {
                neighbours++;
            }
        }
    }
    return neighbours;
}

      

This assumes your method board.get(...)

is ok with values ​​from the edge of the board.



Alternative offset strategies:

  • As above, for (int xOffset = -1; xOffset < 2; xOffset++)

  • Use an open top border: for (int xOffset = -1; xOffset <= 1; xOffset++)

  • Use an array defined elsewhere:

    private static final int[] OFFSETS = { -1, 0, 1 };
    ...
    for (int xOffset : OFFSETS)
    
          

+5


source







All Articles