将1D阵列转换为2D

时间:2018-02-22 21:58:31

标签: java algorithm

我正在尝试打印一维数组给出:

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}

我在分配正确位置时遇到问题,寻求帮助以纠正错误。

1 个答案:

答案 0 :(得分:1)

这有两组循环 - 一组处理对角线右上角的所有值(包括),第二组是对角线左下角的值。 它的尺寸为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 
相关问题