-1

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];

Ryan
  • 133
  • 2
  • 13
  • 3
    I think that would be called a transposition. https://stackoverflow.com/questions/16737298/what-is-the-fastest-way-to-transpose-a-matrix-in-c – markspace Oct 12 '18 at 16:10
  • Thanks, it is a transpose but do you know the solution in Java. – Ryan Oct 12 '18 at 16:12

2 Answers2

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
  • 2
    You 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