2D array - making it "torus" like

1.2k views Asked by At

I am facing following problem:

I have a board of size MxN squares. In Java, what is the best way to make it such that when there are coordinates given which are out of bounds (or with negative values), it will return square from the other side of the board? I am looking for some cleaver use of math. Probably modulus operator, but I'd like it to work for negative values. How to do it right?

For example:

when M = N = 10

//Pseudocode of course
int[10][10] board

//Counting elements from 0, so 10 would normally generate array OOB exception
//I want it to work like this:
board[-1][10] == board[9][0]
1

There are 1 answers

0
aioobe On BEST ANSWER

You would use the modulo operator. A common formula to use (for arbitrarily large positive / negative integers) is:

(n % SIZE + SIZE) % SIZE

Instead of cluttering the code with these formulas however, I would encapsulate it in a function:

int getCell(int i, int j) {
    return board[(i % M + M) % M]
                [(j % N + N) % N];
}