在Java中,如何获取2D数组的值并将它们存储在具有不同列和行大小的另一个2D数组中?

我正在做一个项目,我必须从2D数组制作矩阵.其中一个要求是将3×4 2D阵列(存储的值)转换为6×2 2d阵列(具有相同的值)?

public int[][] covertMatrix(int[][] ma, int r, int c) {
        rw = r;
        col = c;

        this.ma = new int[rw][col];
        for (int i = 0; i < rw; i++) {
            for (int j = 0; j < col; j++) {
                ma[i][j] = ma[i][j];    
            }
        }
        return ma;
}

我已经尝试过这个代码,它重新整形了数组,但只打印了一个零的二维数组.

最佳答案
你有一个像3×4的起始矩阵

+--+--+--+--+
|01|02|03|04|
+--+--+--+--+
|05|06|07|08|
+--+--+--+--+
|09|10|11|12|
+--+--+--+--+

你想要转换为6×2矩阵,如

+--+--+
|01|02|
+--+--+
|03|04|
+--+--+
|05|06|
+--+--+
|07|08|
+--+--+
|09|10|
+--+--+
|11|12|
+--+--+

要做到这一点,显然tab1 [i] [j] = tab2 [i] [j]将无效.您需要在两个数组之间转换地址.乍一看,使用行的模数和col的除法的其余部分就可以了.

就像是

public static void main(String[] args) {
        int[][] tab1 = new int[][]{{1,2,3,4},{5,6,7,8},{9,10,11,12}};
        System.out.println(Arrays.deepToString(tab1));
        System.out.println("---------------------------");
        int size = tab1.length * tab1[0].length;
        for(int i = 1; i <= size; i++){
            int j = size % i;
            if(j == 0){
                convert(tab1, i, size/i);
            }
        }

    }

    private static void convert(int[][] tab1, int row, int col) {
        System.out.println(String.format("converting to %dx%d", row, col));
        int[][] tab2 = new int[row][col];
        for(int i = 0; i < row; i++){
            for(int j = 0; j < col; j++){
                int index = i*col + j;
                int newRow = index / tab1[0].length;
                int newCol = index % tab1[0].length;
                tab2[i][j] = tab1[newRow][newCol];
            }
        }
        System.out.println(Arrays.deepToString(tab2));
        System.out.println("---------------------------");
    }

哪个给出了输出

[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
---------------------------
converting to 1x12
[[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]]
---------------------------
converting to 2x6
[[1, 2, 3, 4, 5, 6], [7, 8, 9, 10, 11, 12]]
---------------------------
converting to 3x4
[[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
---------------------------
converting to 4x3
[[1, 2, 3], [4, 5, 6], [7, 8, 9], [10, 11, 12]]
---------------------------
converting to 6x2
[[1, 2], [3, 4], [5, 6], [7, 8], [9, 10], [11, 12]]
---------------------------
converting to 12x1
[[1], [2], [3], [4], [5], [6], [7], [8], [9], [10], [11], [12]]
---------------------------

转载注明原文:在Java中,如何获取2D数组的值并将它们存储在具有不同列和行大小的另一个2D数组中? - 代码日志