# Avoiding underflow when identifying neighbours of a cell in a grid by using modulo

I'm going through a tutorial that is using the Game of Life as example code. It has a function in it that finds the neighbor of a given cell. It is explained quickly that "When applying a delta of -1, we add self.height - 1 and let the modulo do its thing, rather than attempting to subtract 1" which would require a bunch of conditional logic to check for edge cases (when the cell we are checking is on the edge and simply adding or subtracting from its position would put it out of bounds)... This is the algorithm:

for a given 0-indexed row and col in a 2d space with area width * height:

for delta_row in [height - 1, 0, 1]
for delta_col in [width -1, 0, 1]
if delta_row == 0 && delta_col == 0
continue // this is the cell we are checking

neighbour_row = (row + delta_row) % height
neighbour_col = (col + delta_col) % width


Anyways, I'm just wondering, how does someone figure this out from the naive case, where you just add and subtract and check for bounds? I'm not great with math but I'm assuming there might be a way to explain this algebraically? I worked through this with actual numbers for a while to verify it and just want to get a better understanding of how this works so maybe I can use this concept again later.

Using modular arithmetic here is equivalent to playing the game of life on a torus. Suppose you start with a $$100\times 100$$ grid with rows and columns numbered $$0, \dots, 99$$. The modular arithmetic says that $$0-1\equiv 99$$, which means that row $$99$$ is above row $$0$$ as well as below row $$98$$ and, similarly, column $$99$$ is to the left of column $$0$$ as well as to the right of column $$98$$.
This isn't equivalent to saying that there is nothing above row $$0$$ and nothing below row $$99$$.