Search code examples
javamultidimensional-array2dconways-game-of-lifeneighbours

Counting (8 possible) neighbours in 2D array in conways Game Of Life


I have to count how many "alive" (in this case a char: 'O') neigbours each single cell has. Every cell has 8 neighbours. (It is for "The Game Of Life" from Conway)

"As you can notice, each cell has eight neighbors. We consider the universe to be periodic: border cells also have eight neighbors. For example: Neighbours from a "normal" cell

If cell is right-border, its right (east) neighbor is leftmost cell in the same row. If cell is bottom-border, its bottom (south) neighbor is topmost cell in the same column. Corner cells use both solutions." When a cell is border and when a cell is a top corner

The links are visualizations to how to check the cells in cases of "exceptions".

I found this on the internet:

for (int x = -1; x <= 1; x += 1) {
    for (int y = -1; y <= 1; y += 1) {
        int r = i + y;
        int c = j + x;
        if (r >= 0 && r < n && c >= 0 && c < n
                && !(y == 0 && x == 0)
                && currentUniverse[i][j] == 'O') {
            neighbours++;
        }

However that did not seem to work... I can not come up with a tidy and most of all smart/handy/short piece of code to check how many alive neighbours a cell at a position (let's say currentUniverse[i][j]) has...

Has anyone suggestions, tips or some other help?


Solution

  • Give this one a shot. I am using n as the size of the array (assumes in square).

    int n = 4;
    System.out.println();
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < n; j++) {
            int neighbours = 0;
            for (int x = -1; x <= 1; x += 1) {
                for (int y = -1; y <= 1; y += 1) {
                    if (!(y == 0 && x == 0)) {
                        int r = i + y;
                        int c = j + x;
                        //normalize
                        if (r < 0) r = n - 1;
                        else if (r == n) r = 0;
    
                        if (c < 0) c = n - 1;
                        else if (c == n) c = 0;
                        if (currentUniverse[r][c] == 0)
                            neighbours++;
                    }
                }
            }
            System.out.print("\t" + neighbours);
        }
        System.out.println();
    }