[ Exercises | Chapter Index | Main Index ]

Solution for Programming Exercise 7.2


This page contains a sample solution to one of the exercises from Introduction to Programming Using Java.


Exercise 7.2:

Suppose that M is a two-dimensional array that has R rows and C columns. The transpose of M is defined to be an array T that has C rows and R columns such that T[i][j] = M[j][i] for each i and j. Write a function that takes an array of type int[][] as a parameter, and returns the transpose of that array. (Assume that the parameter is a typical 2D array in which all the rows have the same length.) Also write a subroutine to print a 2D array of integers in neat rows and columns, and include a main() routine to test your work.


Discussion

To create the transpose, we need to know how many rows and how many columns are in the original array. As noted in Subsection 7.6.1, the number of rows in a 2D array A is given by A.length, and the number of columns is A[0].length. (A[0].length is the length of the first row of A, which is the same as the number of columns in A. Remember that all rows have the same length.) Given that, we can create a transpose array of the correct size, and—with a little care to get the indices right—we can copy all the items from the original array into the transpose. If matrix is the original array, then the transpose can be created with

int[][] transpose;
int R = matrix.length;     // the number of rows in matrix
int C = matrix[0].length;  // the number of columns in matrix
transpose = new int[C][R];
for ( int i = 0; i < C; i++) { // goes through ROWS of the transpose
    for ( int j = 0; j < R; j++ ) { // goes through COLUMNS of the transpose
        transpose[i][j] = matrix[j][i];
    }
}

One other note of interest is in the code for printing the array. See the comments on the source code below.

By the way, one purpose of this exercise was to remind you that arrays can be parameters and they can be the return value of a function. In this case, the parameter type and the return type for the function are both given by int[][].


The Solution

public class TransposeMatrix {
    
    /**
     * Creates the transpose of a given 2D array of integers.
     * @param matrix  the original array
     * @return the transpose of matrix
     */
    public static int[][] computeTranspose( int[][] matrix ) {
        int[][] transpose;
        int R = matrix.length;     // the number of rows in matrix
        int C = matrix[0].length;  // the number of columns in matrix
        transpose = new int[C][R];
        for ( int i = 0; i < C; i++) { // goes through ROWS of the transpose
            for ( int j = 0; j < R; j++ ) { // goes through COLUMNS of the transpose
                transpose[i][j] = matrix[j][i];
            }
        }
        return transpose;
    }
    
    /**
     * Prints out the items of a 2D array of ints in rows and columns,
     * with 6 spaces in each column.
     */
    public static void print( int[][] array ) {
            // Note that this uses a for-each loop where the loop
            // control variable is of type int[].  This works because
            // a 2D array is actually a 1D array of 1D arrays, where
            // each 1D array is one of the rows of the 2D array.
        for ( int[] row : array ) { 
                // print out one row from the array
            System.out.print("   ");
            for ( int item : row ) {
                   // print with 1 blank space and 5 spaces for the integer;
                   // if an integer needs more than 5 spaces, the columns will
                   // be messed up, but all the integers will still be readable.
                System.out.printf(" %5d", item); 
            }
            System.out.println();
        }
    }
    
    /**
     * Test the subroutines by creating two arrays and printing them and
     * their transposes.  The arrays are constructed so that it is easy
     * to see that the transposes are correct.
     */
    public static void main(String[] args) {
        int[][] orig = {
                { 1, 2, 3, 4, 5, 6 },
                { 10, 20, 30, 40, 50, 60 },
                { 100, 200, 300, 400, 500, 600 }
        };
        System.out.println("Original matrix:");
        System.out.println();
        print(orig);
        System.out.println();
        System.out.println("The transpose:");
        System.out.println();
        print( computeTranspose(orig) );
        System.out.println();
        System.out.println();

        orig = new int[][] {
                {1, 1, 1, 1, 1, 1, 1},
                {2, 2, 2, 2, 2, 2, 2},
                {3, 3, 3, 3, 3, 3, 3},
                {4, 4, 4, 4, 4, 4, 4},
                {5, 5, 5, 5, 5, 5, 5},
                {6, 6, 6, 6, 6, 6, 6},
                {7, 7, 7, 7, 7, 7, 7},
        };
        System.out.println("Original matrix:");
        System.out.println();
        print(orig);
        System.out.println();
        System.out.println("The transpose:");
        System.out.println();
        print( computeTranspose(orig) );
        System.out.println();

    }

}

[ Exercises | Chapter Index | Main Index ]