Transposing an array (CS 101)

I'm trying to transpose an array from 4x2 to 2x4, per these instructions"

"Given a 2-D array arr1 of ints, return a 2-D array arr2, that is the transpose of arr1. A transpose is when you make the rows of the arrays into columns. That is, arr1[n][m] = arr2[m][n]."

The solution I made follows:

public int[][] transpose(int[][] arr1){
    int[][] arr2;

    arr2 = new int [arr1[0].length][arr1.length];
    for(int i = 0; i<arr1.length; i++){
        for(int j = 0; j < arr1[0].length; j++){
            arr2[j][i] = arr1[i][j];
        }
    }
}

I'm not sure I quite understand the array notation though, when the code references arr1[0] and arr1 to access rows vs columns. Does arr1[0].length access the length of the first column, where arr1.length accesses the length of the first row?

Jon Skeet
people
quotationmark

Does arr1[0].length access the length of the first column, where arr1.length accesses the length of the first row?

It depends one exactly how you're viewing the array in terms of "rows" and "columns".

The int[][] type is an array of arrays. Each element of that array is an int[], which can be a different size to all the others. So arr1.Length is the number of "nested" arrays, and arr1[0].Length is the length of the first nested array. If you're viewing each nested array as a row, then arr1.Length is the number of rows, and arr1[0].Length is the number of columns in the first row - and you're basically assuming that each element of arr1 has the same length.

people

See more on this question at Stackoverflow