Java: 2d array - makes it a "torus" like

I faced the following problem:

I have an M x N board . What is the best way to do this in java so that when given coordinates that are outside (or with negative values) it will return a square on the other side of the board? I am looking for some use of math clover. Probably a modulus operator, but I would 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]

      

+3


source to share


1 answer


You must use the modulo operator. General formula to use (for arbitrarily large positive / negative integers):

(n % SIZE + SIZE) % SIZE

      



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

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

      

+9


source







All Articles