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
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.