Search code examples
javaarraysconways-game-of-life

Issues with reading a 2d Array - Java


I am trying to do Conway's game of life using 2d arrays. This method is supposed to look at every position on a 2d array and check each of its neighbors and count how many neighbors are surrounding the position (0 being empty and 1 being occupied). It then performs some logic and decides if that position is dead or alive. The issue I am having is that by the time it checks the second position the values for the tempMatrix are wrong. I have specifically been checking the first position [0][0] and it changes from 0 to 1 and I have no idea why. Thank you in advance for your help!

public static int[][] Evolve(int[][] _array){
    inputMatrix = _array;
    outputMatrix = inputMatrix;
    int [][] tempMatrix = inputMatrix;
    System.out.println("Output Matrix:");
    for (int x = 0; x < size; x++){
        for (int y = 0; y < size; y++){
            int neighbor_count = 0;
            ArrayList<int[]> neighbors = getNeighbors(x,y);
            for(int[] neighbor: neighbors){
                int tempX = neighbor[0];
                int tempY = neighbor[1];
                int temp = tempMatrix[tempX][tempY];
                if(temp == 1){
                    neighbor_count++;
                }
            }
            if(tempMatrix[x][y] == 1){
                if(neighbor_count == 1 || neighbor_count > 3) {
                    outputMatrix[x][y] = 0;
                }
                else{
                    outputMatrix[x][y] = 1;
                }
            }else if(neighbor_count == 3){
                outputMatrix[x][y] = 1;
            }else{
                outputMatrix[x][y] = 0;
            }
            System.out.printf("%2d ",outputMatrix[x][y]);
        }
        System.out.println();
    }
    return outputMatrix;
}

Solution

  • Your inputMatrix outputMatrix and tempMatrix are referring to the same 2D array. Therefore, when you modify the outputMatrix by the following code

    if(tempMatrix[x][y] == 1){
                if(neighbor_count == 1 || neighbor_count > 3) {
                    outputMatrix[x][y] = 0;
                }
                else{
                    outputMatrix[x][y] = 1;
                }
            }else if(neighbor_count == 3){
                outputMatrix[x][y] = 1;
            }else{
                outputMatrix[x][y] = 0;
            }
    

    The value of the tempMatrix also changes. Thus, try to make new 2D array for all the three matrices and then copy the value.

    int inputMatrix[][]=new int[dimension][dimension];
    

    Now copy the value of _array matrix to the inputMatrix.