Transpose a matrix
Description: Transpose the matrix {{1,2,3},{4,5,6}}. The result must be {{1,4},{2,5},{3,6}}.
Hint:
- The new matrix has
columnsrows androwscolumns. Copym[i][j]tot[j][i].
Solution
import java.util.Arrays;
public class Main {
static int[][] transpose(int[][] m) {
int rows = m.length, cols = m[0].length;
int[][] t = new int[cols][rows];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < cols; j++) {
t[j][i] = m[i][j];
}
}
return t;
}
public static void main(String[] args) {
int[][] m = {{1, 2, 3}, {4, 5, 6}};
System.out.println(Arrays.deepToString(transpose(m)));
}
}
Output
[[1, 4], [2, 5], [3, 6]]
How it works
- A 2 x 3 matrix becomes a 3 x 2 matrix, so a new array with the sizes swapped is needed.
Read Multidimensional Arrays.
Learn more about the similar topics:
| Tutorials |
|---|
| No Content Found. |
| Exercises & Assignments |
|---|
| No Content Found. |
| Interview Questions & Answers |
|---|
| No Content Found. |