mirror of https://github.com/evanferrao/dsa
add transpose matrix
This commit is contained in:
parent
46d112fd98
commit
433e4880e3
|
|
@ -0,0 +1,60 @@
|
|||
// write a code to transpose a matrix using function transposeMatrix(int[][] matrix) in java
|
||||
|
||||
import java.util.Scanner;
|
||||
|
||||
calss TransposeMatrix {
|
||||
public static void main(String args[]) {
|
||||
Scanner sc = new Scanner(System.in);
|
||||
System.out.println("Enter the number of rows: ");
|
||||
int rows = sc.nextInt();
|
||||
System.out.println("Enter the number of columns: ");
|
||||
int cols = sc.nextInt();
|
||||
int matrix[][] = new int[rows][cols];
|
||||
System.out.println("Enter the elements of the matrix: ");
|
||||
for (int i = 0; i < rows; i++) {
|
||||
for (int j = 0; j < cols; j++) {
|
||||
matrix[i][j] = sc.nextInt();
|
||||
}
|
||||
}
|
||||
System.out.println("The matrix is: ");
|
||||
for (int i = 0; i < rows; i++) {
|
||||
for (int j = 0; j < cols; j++) {
|
||||
System.out.print(matrix[i][j] + " ");
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
int[][] result = transposeMatrix(matrix);
|
||||
System.out.println("The transpose of the matrix is: ");
|
||||
for (int i = 0; i < cols; i++) {
|
||||
for (int j = 0; j < rows; j++) {
|
||||
System.out.print(result[i][j] + " ");
|
||||
}
|
||||
System.out.println();
|
||||
}
|
||||
}
|
||||
|
||||
public static int[][] transposeMatrix(int[][] matrix) {
|
||||
int rows = matrix.length;
|
||||
int cols = matrix[0].length;
|
||||
int[][] result = new int[cols][rows];
|
||||
for (int i = 0; i < cols; i++) {
|
||||
for (int j = 0; j < rows; j++) {
|
||||
result[i][j] = matrix[j][i];
|
||||
}
|
||||
}
|
||||
return result;
|
||||
}
|
||||
|
||||
public static int[][] transposeOriginalMatrix(int[][] matrix) {
|
||||
int rows = matrix.length;
|
||||
int cols = matrix[0].length;
|
||||
for (int i = 0; i < rows; i++) {
|
||||
for (int j = i + 1; j < cols; j++) {
|
||||
int temp = matrix[i][j];
|
||||
matrix[i][j] = matrix[j][i];
|
||||
matrix[j][i] = temp;
|
||||
}
|
||||
}
|
||||
return matrix;
|
||||
}
|
||||
}
|
||||
Loading…
Reference in New Issue