【问题标题】:Swapping Rows and Columns of 2D Array [duplicate]交换二维数组的行和列
【发布时间】:2017-09-27 03:30:27
【问题描述】:

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

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

【问题讨论】:

  • 这是一个正方形,又名nxn 数组吗?
  • @AyushGupta 是的,总是一个方阵,最大 10x10

标签: java algorithm matrix


【解决方案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;
}

【讨论】:

    猜你喜欢
    • 2020-03-30
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多