mirror of https://github.com/evanferrao/dsa
59 lines
1.9 KiB
Java
59 lines
1.9 KiB
Java
// write a code to transpose a matrix using function transposeMatrix(int[][] matrix) in java
|
|
|
|
import java.util.Scanner;
|
|
|
|
class 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 void 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;
|
|
}
|
|
}
|
|
}
|
|
} |