Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Making a 2D array toroidal

How can I make the array toroidal (wrap bottom to top and left to right), i.e the leftmost cell is regarded as the rightmost cell, like [0][0] and [5][5] are the same cells in int array[5][5]

like image 359
Finlandia_C Avatar asked Oct 24 '25 15:10

Finlandia_C


1 Answers

The 'toridiality' (if that is actually a word) could be implemented by using an accessor function which does the mapping (by using the division remainder operator) instead of the bracket operators on the arrays directly. The function could be implemented as follows, where m and n are the number of rows and columns of board, respectively.

int GetElement(int i, int j)
{
    return board[i % m][j % n];
}
like image 171
Codor Avatar answered Oct 26 '25 04:10

Codor



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!