Multi-dimensional array transposing
I saw that all of the answers create a new resultant matrix. This is simple:
matrix[i][j] = matrix[j][i];
However, you can also do this in-place, in case of square matrix.
// Transpose, where m == n
for (int i = 0; i < m; i++) {
for (int j = i + 1; j < n; j++) {
int temp = matrix[i][j];
matrix[i][j] = matrix[j][i];
matrix[j][i] = temp;
}
}
This is better for larger matrices, where creating a new resultant matrix is wasteful in terms of memory. If its not square, you can create a new one with NxM
dimensions and do the out of place method. Note: for in-place, take care of j = i + 1
. It's not 0
.
The following solution does in fact return a transposed array instead of just printing it and works for all rectangular arrays, not just squares.
public int[][] transpose(int[][] array) {
// empty or unset array, nothing do to here
if (array == null || array.length == 0)
return array;
int width = array.length;
int height = array[0].length;
int[][] array_new = new int[height][width];
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
array_new[y][x] = array[x][y];
}
}
return array_new;
}
you should call it for example via:
int[][] a = new int[][]{{1, 2, 3, 4}, {5, 6, 7, 8}};
for (int i = 0; i < a.length; i++) {
System.out.print("[");
for (int y = 0; y < a[0].length; y++) {
System.out.print(a[i][y] + ",");
}
System.out.print("]\n");
}
a = transpose(a); // call
System.out.println();
for (int i = 0; i < a.length; i++) {
System.out.print("[");
for (int y = 0; y < a[0].length; y++) {
System.out.print(a[i][y] + ",");
}
System.out.print("]\n");
}
which will as expected output:
[1,2,3,4,]
[5,6,7,8,]
[1,5,]
[2,6,]
[3,7,]
[4,8,]