Finlandia_C
Finlandia_C

Reputation: 395

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]

Upvotes: 3

Views: 2414

Answers (1)

Codor
Codor

Reputation: 17605

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];
}

Upvotes: 4

Related Questions