【问题标题】:Unable to convert between 1d and 2d array values无法在 1d 和 2d 数组值之间转换
【发布时间】: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,将这个问题标记为已解决的可接受方法是什么?

标签: java arrays matrix 2d


【解决方案1】:

所有数组都从 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)

【讨论】:

  • 数组以0开头是对的。另请注意,在大卫的回答中,他打印的索引以 0 开头。在您的示例输出中,您的第一个索引输出为 5。
  • 谢谢!是的,索引是问题。我仍然需要 1 作为索引,因为它会插入其他需要它的东西,但是我通过在转换期间增加大小来解决问题。
【解决方案2】:

看起来您在错误情况下交换了 x 和 y。位置应该是 19,而不是 16。

Position [4,3] in a 4x4 array is (4*4)+3 = 19
floor(19 / 4) = 4
19 % 4 = 3 

出于学习数组的目的,我强烈建议坚持使用零索引数组,因为它们更直观地与内容在内存中的实际存储方式相关联。

【讨论】:

    猜你喜欢
    • 2013-10-27
    • 2017-07-29
    • 1970-01-01
    • 2022-01-17
    • 1970-01-01
    • 1970-01-01
    • 2019-12-15
    • 2017-09-11
    • 1970-01-01
    相关资源
    最近更新 更多