【发布时间】:2015-06-23 13:44:30
【问题描述】:
我意识到这个问题和解决方案遍布 StackOverflow like here 但是我仍然无法完成这项工作。
大多数示例说我只需要将行乘以宽度并添加列,这意味着 4x4 方形网格中的位置 (4, 3) 将变为 (3 * 4 + 4) 或 16。到目前为止太好了。
示例说要取回坐标,我应该将索引除以 x 的行数,然后得到 y 的索引的模数。对于上面的例子,那应该是……
int x = 16 / 4;
int y = 16 % 4;
但这适用于某些值,而不适用于其他值。在这种情况下,当我在转换为索引后取回坐标时,我得到 (4,0)。这是有道理的,因为 4 均匀地进入了 16,所以我一定错过了一些基本的东西。
这是我创建的一些测试 Java 代码,用于解决这个问题。我应该提到我从 1 开始索引,所以左上角的第一个方块是 1,1,最后一个方块是 4,4。
public class Test {
int size;
public Test(int size) {
this.size = size;
}
public int toIndex(int x, int y) {
return x * this.size + y;
}
public int[] toCoordinates(int index) {
int coordinates[] = new int[2];
coordinates[0] = index / this.size;
coordinates[1] = index % this.size;
return coordinates;
}
public static void main(String[] args) {
int testSize = 4;
Test test = new Test(testSize);
for (int i = 1; i <= testSize; i++) {
for (int j = 1; j <= testSize; j++) {
int index = test.toIndex(i, j);
int coordinates[] = test.toCoordinates(index);
System.out.println(index + " == " + coordinates[0] + "," + coordinates[1]);
}
}
}
}
当前代码的输出是
5 == 1,1
6 == 1,2
7 == 1,3
8 == 2,0
9 == 2,1
10 == 2,2
11 == 2,3
12 == 3,0
13 == 3,1
14 == 3,2
15 == 3,3
16 == 4,0
17 == 4,1
18 == 4,2
19 == 4,3
20 == 5,0
【问题讨论】:
-
左上角是 0,0,右下角是 3,3。 0 是第一个数字!
-
我猜你的困惑源于使用 1 索引数组。 Java 使用 0 索引数组,我强烈建议您也这样做。
-
就是这样!我只需要在计算时将大小加 1。
-
我已经有一段时间没有使用 SO了,因为这些是 cmets,将这个问题标记为已解决的可接受方法是什么?