gpt4 book ai didi

java - 循环遍历二维数组(对角线)?

转载 作者:行者123 更新时间:2023-12-02 14:33:52 26 4
gpt4 key购买 nike

我有一个 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]);
}
}

此外,我还需要获取所有对角线的接下来的四个值,这些值也来自底部的 upstaris,但我不知道如何制作它..

编辑:这是另一个例子:

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++;
}

关于java - 循环遍历二维数组(对角线)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35959697/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com