I need to swap rows and columns of a 2D array using Java. I have an ArrayList
that tells me where a certain row and column needs to go. For example:
ArrayList<Integer> = [2, 0, 1, 3]
0 1 2 3 (indexes for illustration)
The above means that row 0 and column 0 need to become row 2 and column 2, row 1 and column 1 need to become row 0 and column 0, and so on.
For example:
int[][] example = {
{0, 3, 3, 4},
{0, 1, 0, 0},
{0, 0, 1, 0},
{8, 1, 1, 0}
};
Let's say we swap rows first, so the "intermediate" form would be:
// From the list, change rows as follows:
// 0->2, 1->0, 1->2, 3->3
int[][] example = {
{0, 1, 0, 0},
{0, 0, 1, 0},
{0, 3, 3, 4},
{8, 1, 1, 0}
};
Finally, swapping columns, we get the desired output:
// From the list, change columns as follows:
// 0->2, 1->0, 1->2, 3->3
int[][] example = {
{1, 0, 0, 0},
{0, 1, 0, 0},
{3, 3, 0, 4},
{1, 1, 8, 0}
};
Note that the swapping may be in place or in a new matrix, does not matter. I'm stuck in the part where I need to swap the columns, I'm not too sure how to proceed here. This is what I've tried so far:
public static int[][] makeStandardForm(int[][] m){
//generate list of index swaps
List<Integer> l = new ArrayList<Integer>(orderIndexes(m));
int[][] m1 = new int[m.length][m.length];
//Swap rows, working fine
for(int i=0; i < m.length; i++){
m1[i] = m[(int)l.get(i)];
}
//Swap columns, stuck here?
for(int i=0; i < m.length; i++){
//don't know how to swap columns
}
return m1;
}