How do I make this wrap around function work in java?

Viewed 28

Hi I am trying to check the surrounding neighbours of a cell using this function, and I need it to logically wrap around the grid to count the amount of 1s in the surrounding 8 cells.

This is the code I have so far. I know I am supposed to use modulo for this to work but I have no idea how that would work, more importantly I have no idea how to implement it in this function. I also know that I am supposed to do something like r - 1 and y - 1 to check the cells, but again I have no idea how that works with modulo

The if statement above is my attempt at doing this, but I clearly lack understanding of what I am doing.

Currently, this function goes through each cell on the grid using the 2 for loops. Beyond that, I need it to check the surrounding 8 cells for "1"s, and on the border, I need it to check the other side of the grid (i.g. wrap around as if the grid was spherical).

Can someone please explain and give me a solution to this? Greatly appreciate any help.

public static int countNeighbours(int row, int col, Board b)
    {
        int count = 0;
        for (int r = row - 1; r <= row + 1; r++)
        {
            for (int c = col - 1; c <= col + 1; c++)
            {
                
                    
                    
               if (b.get(r - 1 + row) % row)((c - 1 + col) % col) = 1); {
                    count++;
                }
            }
        }
        return count;
    } 
0 Answers
Related