java - 无法在一维和二维数组值之间转换

标签 java arrays matrix 2d

我意识到这个问题和解决方案遍布 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/

相关文章:

java - 我应该对从父类(super class)继承的方法进行单元测试吗?

sql - 使用 PostgreSQL,我如何获取数组中某个项目的第一列的值?

c - C 中数组索引+索引值的用户输入

arrays - 多维数组在内存中的表示

python - Numpy 中的特征向量 : Very bad numerics? 我做错了什么吗?

java - 无法在intelliJ中运行java代码并且无法解析build.gradle符号

java - 从服务中检索的日期格式

java - Selenium Find By Xpath 返回错误的元素

java - 索引越界异常但无法找出问题所在

python - 在 python 中计算稀疏矩阵的广义特征值