Java multidimensional array transpose

I have a row based multidimensional array:

/** [row][column]. */
public int[][] tiles;

I want to convert this array to a column based array, as follows:

/** [column][row]. */
public int[][] tiles;

... but I really don't know where to start

Solution

Try this:

@Test
    public void transpose() {

        final int[][] original = new int[][] { { 1,2,3,4 },{ 5,6,7,8 },{ 9,10,11,12 } };
        for (int i = 0; i < original.length; i++) {
            for (int j = 0; j < original[i].length; j++) {
                System.out.print(original[i][j] + " ");
            }
            System.out.print("\n");
        }
        System.out.print("\n\n matrix transpose:\n");
        // transpose
        if (original.length > 0) {
            for (int i = 0; i < original[0].length; i++) {
                for (int j = 0; j < original.length; j++) {
                    System.out.print(original[j][i] + " ");
                }
                System.out.print("\n");
            }
        }
    }

Output:

1 2 3 4 
5 6 7 8 
9 10 11 12 


 matrix transpose:
1 5 9 
2 6 10 
3 7 11 
4 8 12
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>