繁体   English   中英

遍历2D阵列的对角线

[英]Iterating through the subdiagonal of a 2D Array

我正在尝试遍历随机生成的0和1的2d数组。 在我坚持的这种方法中,我试图查看对角线是否具有相同的数字,全1,全0或不同的数字。

子对角线含义:

110

101

011

0是对角线。

这是我到目前为止的代码。 我试图从最后一行开始迭代,对角线计数到第一行。

int firstValue= matrix[matrix.length-1][0];
    int result = -1;
    for(int row = matrix.length-1; row > 0; row--)
    {
        int column = row;
        if(firstValue == matrix[row][column])
        {
            result = firstValue;
            continue;
        }
        else
        {
            result = -1;
            break;
        }
    }
    if(result== 1)
    {
        System.out.println("All " + firstValue + "s on the subdiagonal");
    }
    else if (result == 0)
    {
        System.out.println("All " + firstValue + "s on the subdiagonal");
    }
    else
    {
        System.out.println("Numbers on subdiagonal are different");
    }
}

我几乎可以确定我的问题是firstValue和/或for循环计数对角线。 任何帮助,将不胜感激,非常感谢

您的问题似乎在以下几行,

for(int row = matrix.length-1; row > 0; row++) {
    ...
}

你正在做一个

row = matrix.length-1; // row = array length - 1
row++ //this will increase the row's value beyond your array length

然后,您将访问一个不存在的索引,导致ArrayIndexOutOfBoundsException

编辑

你想做的是

for(int row = matrix.length-1; row >= 0; row--) {
    ....
}

这样,您就可以从最大索引到最小索引(0)遍历数组。

编辑2

假设称为arr的Staring数组具有4个元素。 它的结构如下

arr[0] = "test1";
arr[1] = "test2";
arr[2] = "test3";
arr[3] = "test4";

数组索引始终从0开始,因此上述数组中的最高索引为3。

因此,如果您要从最小的索引迭代到最大的索引,则可以

for(int i = 0; i < arr.length; i++) {
    //i's initial value is 0 and itll increment each time the loop runs
    //loop will terminate when i is no longer < 4
    System.out.println(arr[i]);
}

并以相反的顺序遍历数组,

for(int i = (arr.length - 1); i <= 0; i--) {
    //i's initial value is (4 - 1) and it'll decrement each time the loop runs
    //loop will terminate when i smaller or equal to 0
    System.out.println(arr[i]);
}

因此,我们要检查对角线中的所有值是否都相同,如果是,那么我们要打印相同的值。 首先我们搁置一个比较以检查其他指标

int checkValue = arr[0][arr[0].length-1];

这是第一行中的最后一个值。 然后,我们设置一个标记以在我们正在检查的索引与第一个值匹配时进行捕获。 我们将其设置为false,因为我们假设值不匹配。

boolean flag = false;

现在我们有了这个,我们需要遍历数组中的每一行。 我们将从第二行(arr [1])开始,然后我们需要将值与上次检查的值(arr [1] [arr.length-1-i])进行比较,然后向下和向上检查一个值。 如果我们的第一个值(我们将其值分配给checkValue)和我们要检查的值相同,则将标志更改为true。

for (int i = 1; i < arr.length; i++)
    if (arr[i][arr.length - 1 - i] != checkValue)
        flag = true;

这将遍历数组中的所有行。 现在,我们必须检查标志的状态并打印出适当的响应。 如果该标志为true,则打印出该行上的值相同。 否则,我们将说次对角线一直都不匹配。

if (!flag)//remember our flag is set to false, double negative equals true.
    System.out.println("All of the values on the subdiagonal are the same");
else
    System.out.println("All of the values on the subdiagonal are not the same");

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM