[英]Swapping Rows and Columns of 2D Array
I need to swap rows and columns of a 2D array using Java. 我需要使用Java交换2D数组的行和列。 I have an ArrayList
that tells me where a certain row and column needs to go. 我有一个ArrayList
告诉我某个行和列需要去哪里。 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. 上面的意思是第0行和第0列需要成为第2行和第2列,第1行和第1列需要成为第0行和第0列,依此类推。
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;
}
You have to copy column values one by one. 您必须一一复制列值。
Try this 尝试这个
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];
int[][] m2 = 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++){
for (int j = 0; j < m.length; j++) { // I used the fact that matrix is square here
m2[j][i] = m1[j][l.get(i)];
}
}
return m2;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.