繁体   English   中英

遍历2D数组(对角线)?

[英]Looping through a 2D array (diagonal)?

我有一个6x6数组,想始终获取下一个四个值。 举个例子:

0-----
-1----
--2---
---3--
----4-

所以我想得到所有对角线的(0 + 1 + 2 + 3)和(1 + 2 + 3 + 4)的总和。

我尝试了一些东西,但不幸的是,我只得到了第一个对角线(从左上角到楼下):

for (int i = 0; i < 3; i++) {
            for (int j = 4; j >= 0; j--) {
                    dosomething..(array[j][i]);
                    dosomething..(array[i + 1][j + 1]);
                    dosomething..(array[i + 2][j + 2]);
                    dosomething..(array[i + 3][j + 3]);
            }
        }

另外,我还需要获取所有对角线的下四个值,这也来自对角向上角,而且我不知道如何制作。

编辑:这是另一个示例:

A B C D E F
G H I J K L
M N O P Q R
S T U V W X
Y Z 1 2 3 4
6 7 8 9 10 11

我现在想要的是以下内容:

我想得到:

(A,H,O,V)

(H,O,V,3)

(O,V,3,11)

(C,J,Q,X)

(B,I,P,W)

(I,P,W,4)

对于所有从楼上的对角线延伸的对角线也是如此。

如果数组是正方形,请尝试以下操作:

for (int i=0; i<array[0].length; i++) {
    dosomething..(array[i][i]);
}

在数组不是正方形的情况下:

int i=0;
while (i<Math.min(array[0].length,array.length)) {
    System.out.println(array[i][i]);
    i++;
}

您的矩阵独立数是00、11、22、33,那么您需要这样的东西

for (int i=0; i<array[0].length; i++) {
    dosomething..(array[i][i]);
}

这是一个示例代码,仅用于说明算法。 我不是Java开发人员,因此您应该修复与该语言相关的一些问题。

int table[][];

public int diagonalSum(int index, int max, bool down) {
    if (index <= max) {
        int nextIndex = index + (down ? -1 : 1);
        return table[index][index] + diagonalSum(nextIndex, max, down);
    }
}

int firstDown = diagonalSum(0, table.length, true);
int secondDown = diagonalSum(1, table.length, true);

int firstUp = diagonalSum(table.length, table.length, false);

在for循环语句中似乎存在问题,如果尝试运行此循环并打印j和i的值,您将看到这些对是类似这样的。

  • 4 0
  • 3 0
  • 2 0
  • 1 0
  • 0 0
  • 4 1
  • 3 1等等。

因此,每当尝试访问array[j][i] ,都不会得到对角线元素。 使用对角元素的i和j值相同的事实。

    for (i = 0; i < 4; i++) {
                s1=s1+array[i][i];
                s2=s2+array[i + 1][i + 1];
                s3=s3+array[i + 2][i + 2];}  

尝试这样的事情。 循环进行3圈,因为对于6 * 6数组,如果从0,0开始向下,则4个连续元素对角线的数量为3。 s1,s2,s3用于保存每转的总和。 希望能帮助到你。

这是我如何解决问题的方法。

我将问题分为两部分。 首先是从数组中获取一个值。 第二个是循环4次以递增顺序获取值。

第1部分从数组中获取值。

char getValue(int row, int col)
{
   // add code here to range check the row and col
   return this.myArray[row, col];
}

第2部分循环4次以按升序或降序获得值。

char[] getValues(int startRow, int startCol, boolean goUp)
{
   char[] values = new int[4];
   int row = startRow; 
   int col = startCol;
   // get the 4 values
   for (i = 0; i < values.length(); i++)
   {
      values[i] = getValue(row, col);
      // check if going upstairs or downstairs
      if (goUp)
      {
         row = row + 1;
         col = col + 1;
      }
      else
      {
         row = row - 1;
         col = col - 1;
      }
   }
}

现在,获取值很简单。 只需使用起始行和列调用getValues()。

例如:

char values[] = getValues(0, 0, False);

暂无
暂无

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

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