简体   繁体   中英

Swapping Rows and Columns of 2D Array

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM