2017-09-27 52 views
0

我需要使用Java交换二维数组的行和列。我有一个ArrayList,告诉我某个行和列需要去哪里。例如:交换2D阵列的行和列

ArrayList<Integer> = [2, 0, 1, 3] 
         0 1 2 3 (indexes for illustration) 

上面意味着行0和列0的需要,成为第2行和第2栏,第1行和第1列需要成为行0和列0,依此类推。

例如:

int[][] example = { 
    {0, 3, 3, 4}, 
    {0, 1, 0, 0}, 
    {0, 0, 1, 0}, 
    {8, 1, 1, 0} 
}; 

比方说,我们第一次换行,因此 “中间” 的形式是:

// 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} 
}; 

最后,交换列,我们得到所需的输出:

// 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} 
}; 

请注意,交换可能在位或在一个新的矩阵中,无所谓。 我被困在需要交换列的部分,我不太确定如何在这里继续。 这是我到目前为止已经试过:

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; 
} 
+0

这是一个正方形,又名'n'x'n'阵列? –

+0

@AyushGupta一直是方阵,最大10x10 – alejandrogiron

回答

1

你要复制的列值一个接一个。

试试这个

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; 
} 
+0

非常好的解决方案,非常感谢! – alejandrogiron