简体   繁体   中英

Given a matrix, find the transpose of a matrix

Given a matrix, find the transpose of a matrix. Input: 2 4 12 34 29-12 Where First line represents the number of rows as M. Second line represents the number of columns as N. Third line contains matrix elements of 1st row and so on.

Here is the code:

public static int[][] transpose(int[][] array, int row, int column) {
    int[][] transposed_array = new int[column][row];
    for(int i=0; i<row; i++)
        for(int j=0; j<column; j++)
    transposed_array[j][i] = array[i][j];
    return transposed_array;
}

How does it work?

     public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int row = sc.nextInt();
        int column = sc.nextInt();

        int[][] array = new int[row][column];
        for(int i=0; i<row; i++)
            for(int j=0; j<column; j++) 
                array[i][j] = sc.nextInt();
        
        System.out.println("Original Array: ");
        for(int[] array_row : array)
            System.out.println(Arrays.toString(array_row));

        System.out.println("Transposed Array: ");
        int[][] transposed_array = transpose(array,row,column);
        for(int[] transposed_row : transposed_array)
            System.out.println(Arrays.toString(transposed_row));
        
    }

You need add the following lines at the top of program.

import java.util.Arrays;
import java.util.Scanner;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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