I\'m trying to write a method for \'transpose\' a two-dimensional array of integers, in which the rows and columns of the original matrix are exchanged.
However, I have n
int m = 4;
int n = 5;
// original matrix
int[][] arr1 = {
{11, 12, 13, 14, 15},
{16, 17, 18, 19, 20},
{21, 22, 23, 24, 25},
{26, 27, 28, 29, 30}};
// transposed matrix
int[][] arr2 = new int[n][m];
// swap rows and columns
IntStream.range(0, n).forEach(i ->
IntStream.range(0, m).forEach(j ->
arr2[i][j] = arr1[j][i]));
// output to the markdown table
String matrices = Stream.of(arr1, arr2)
.map(arr -> Arrays.stream(arr).map(Arrays::toString)
.collect(Collectors.joining("
")))
.collect(Collectors.joining("
| ")); System.out.println("| original matrix | transposed matrix |"); System.out.println("|---|---|"); System.out.println("|" + matrices + "|");
original matrix | transposed matrix |
---|---|
[11, 12, 13, 14, 15] |
[11, 16, 21, 26] |
See also: Printing a snake pattern using an array