Game of Life ArrayIndexOutofBounds

前端 未结 2 397
再見小時候
再見小時候 2021-01-27 07:32

I\'m doing the Conway\'s game of life. I\'m pretty sure I\'m close to finished, but when I run it, I get Exception in thread \"main\" java.lang.ArrayIndexOutOfBoundsExcep

相关标签:
2条回答
  • 2021-01-27 07:47

    As I can see, you basically have two choices:

    1. apply finite bounds, that is, for the cells in the first and last columns and rows, you implement an additional check when counting the number of 'living' neighbours.

    2. apply periodic bounds, that is, the cells on the leftmost column and the cells on the rightmost column are considered as neighbours. With the help of modular arithmetic, these cells don't need to be handled separately from others.

    0 讨论(0)
  • 2021-01-27 07:53

    When r is 0, this one is not valid: old[r - 1][c].
    Thus you get the exception you posted.

    I suggest you simplify it like this.

        boolean isValidPosition(int r, int c){
            return 
                0 <= r && r < N &&
                0 <= c && c < M;
    
        }
    
        int getNeighboursCount(boolean[][] old, int r, int c){
            int neighbors = 0;
            for (int i=-1; i<=1; i++){
                for (int j=-1; j<=1; j++){
                    if (i!=0 || j!=0){
                        if (isValidPosition(r + i, c + j)){
                            if(old[r + i][c + j])
                            {
                                neighbors++;
                            }
                        }
                    }
                }
            }
            return neighbors;
        }
    
    0 讨论(0)
提交回复
热议问题