我正在尝试打印给定的一维数组:
int[] D1 = new int[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25};
int n = 5;
我的预期输出是:
{11, 7, 4, 2, 1},
{16, 12, 8, 5, 3},
{20, 17, 13, 9, 6},
{23, 21, 18, 14, 10},
{25, 24, 22, 19, 15}
这是我的方法:
cnt = 0;
for (int i = 0; i < n; i++) {
for (int j = n-1; j >= 0; j--) {
a[i][j] = D1[cnt];
cnt++;
}
}
这导致:
{ 5, 4, 3, 2, 1},
{10, 9, 8, 7, 6},
{15, 14, 13, 12, 11},
{20, 19, 18, 17, 16},
{25, 24, 23, 22, 21}
我在分配正确的位置时遇到问题,正在寻求帮助来纠正这个问题。
这有两组循环 - 一组处理对角线右上角(包括)的所有值,第二组处理对角线左下角的值。它针对 4x4、5x5 和 6x6 的尺寸进行了测试。
public class SquareMatrix {
public static void main(String[] args) {
//int[] D1 = new int[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16};
int[] D1 = new int[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25};
//int[] D1 = new int[]{ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36};
int n = 5;
int[][] m = new int[n][n];
int cnt = 0;
// The top right part of the matrix (values 1-15 in a 5x5 scenario)
for (int i = 1; i <= n; i++) {
for (int j = 0; j < i; j++) {
m[j][n+j-i] = D1[cnt++];
}
}
// The bottom left of the matrix (values 16-25 in a 5x5 scenario)
for (int i = n-1; i >= 1; i--) {
for (int j = i; j >= 1; j--) {
m[n-j][i-j] = D1[cnt++];
}
}
printMatrix(m);
}
static void printMatrix(int[][] m) {
for (int i = 0; i<m.length; i++) {
for (int j = 0; j<m.length; j++) {
System.out.printf("%2d ", m[i][j]);
}
System.out.println();
}
}
}
为 5x5 生产:
11 7 4 2 1
16 12 8 5 3
20 17 13 9 6
23 21 18 14 10
25 24 22 19 15
和 6x6
16 11 7 4 2 1
22 17 12 8 5 3
27 23 18 13 9 6
31 28 24 19 14 10
34 32 29 25 20 15
36 35 33 30 26 21
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句