2D数组 - 将其制作成“环面”的形式

3
我面临以下问题:
我有一个大小为M xN的方格板。在Java中,如何最好地使得当给出超出边界(或带有负值)的坐标时,它将返回来自棋盘另一侧的方格?我正在寻找一些聪明的数学运用。可能是模运算符,但我希望它也适用于负值。如何正确地实现?
例如:
当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个回答

10

您可以使用取模运算符。一个常用的公式是(适用于任意大的正/负整数):

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接