java multi-dimensional array transposing

后端 未结 11 2158
谎友^
谎友^ 2020-12-10 11:42

I have a row-based multidimensional array:

/** [row][column]. */
public int[][] tiles;

I would like to transform this array to column-based

11条回答
  •  無奈伤痛
    2020-12-10 12:16

    Use this function (replace String by int if necessary). It takes the matrix as string array and returns a new matrix which is the transpose. It checks for the edge case of an empty array, too. No prints.

    private String[][] transposeTable(String[][] table) {
        // Transpose of empty table is empty table
        if (table.length < 1) {
            return table;
        }
    
        // Table isn't empty
        int nRows = table.length;
        int nCols = table[0].length;
        String[][] transpose = new String[nCols][nRows];
    
        // Do the transpose
        for (int i = 0; i < nRows; i++) {
            for (int j = 0; j < nCols; j++) {
                transpose[j][i] = table[i][j];
            }
        }
    
        return transpose;
    }
    

提交回复
热议问题