简体   繁体   English

将一维数组转换为二维数组

[英]Converting 1D Array to 2D

I am trying to print a 1D Array Given:我正在尝试打印给定的一维数组:

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;

My Expected Output is:我的预期输出是:

    {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}

This is my method:这是我的方法:

cnt = 0;
for (int i = 0; i < n; i++) {
    for (int j = n-1; j >= 0; j--) {
        a[i][j] = D1[cnt];
        cnt++;
    }
}

which results in:这导致:

    { 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}

I'm having trouble assigning the correct positions, looking for help to correct this.我在分配正确的位置时遇到问题,正在寻求帮助来纠正这个问题。

This has two sets of loops - one dealing with all the values to the top right of the diagonal (inclusive), and the second one the values to the bottom left of the diagonal.这有两组循环 - 一组处理对角线右上角(包括)的所有值,第二组处理对角线左下角的值。 It is tested for sizes 4x4, 5x5 and 6x6.它针对 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();
    }
}

}

producing for the 5x5:为 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 

and 6x6和 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 

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

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