我意识到这个问题和解决方案遍布 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 开始,因此左上角的第一个方 block 是 1,1,最后一个方 block 是 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 开始,试试这个:
public static void main(String[] args) {
int testSize = 4;
Test test = new Test(testSize);
for (int i = 0; i < testSize; i++) {
for (int j = 0; j < testSize; j++) {
int index = test.toIndex(i, j);
int coordinates[] = test.toCoordinates(index);
System.out.println(index + " == " + coordinates[0] + "," + coordinates[1]);
}
}
}
输出:
0 == 0,0
1 == 0,1
2 == 0,2
3 == 0,3
4 == 1,0
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 (16th)
关于java - 无法在一维和二维数组值之间转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31004497/