I would like to completely inverse the x and y coordinates of a two dimensional array in Java. Also, it can inverse a two dimensional array with different length. For example: array[row][column] = array[column][row];
Asked
Active
Viewed 1,404 times
2 Answers
1
This operation is only possible if both dimensions are equal. If so, loop through each row, and then swap for all column positions larger than the row.
So, let's say you have a 3x3 array, you want to swap:
first loop: 0,1 with 1,0 0,2 with 2,0
second loop: 1,2 with 2,1
third loop: nothing to do
To loop use for
. To pick up the length of a given array, use array.length
. To swap, make a temp variable. For example:
int x = array[c][r];
array[c][r] = array[r][c];
array[r][c] = x;
that'll swap [c,r] and [r,c] around.

rzwitserloot
- 85,357
- 5
- 51
- 72
-
2You can do this operation if the dimensions are not equal too. But it will not be in place. If this isn't really a requirement, just create another array with the dimensions swapped and iterate over the original array assigning each element at index `[c] [r] ` to the element at index `[r] [c]` of the new array – Hemerson Tacon Oct 12 '18 at 16:20
0
You can use something like that
public static int[][] transpose(int[][] matrix)
{
int m = matrix.length;
int n = matrix[0].length;
int[][] transposedMatrix = new int[n][m];
for(int i = 0; i < n; i++)
{
for(int j = 0; j < m; j++)
{
transposedMatrix[i][j] = matrix[j][i];
}
}
return transposedMatrix;
}

veben
- 19,637
- 14
- 60
- 80