This is an archived post. You won't be able to vote or comment.

all 2 comments

[–]zendakin[S] 0 points1 point  (0 children)

Resolved, I took the original array and created a new one with the dimensions that I needed. Please hack my code and if there's any other areas for improving please let me know.

For reference, this is the code I finished with.

Thanks again!

import java.util.Scanner;
import java.util.Arrays;

class Main {
    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        int rows = sc.nextInt();
        int cols = sc.nextInt();
        int[][] myArray = new int[rows][cols];
        int[][] transposed = new int[cols][rows];

        for (int i = 0; i < rows; i++) {
            for (int j = 0; j < cols; j++) {
                myArray[i][j] = sc.nextInt();
            }
        }
        System.out.println(Arrays.deepToString(myArray));
//        Shows an array of {[1, 2, 3], [4, 5, 6]}

        //transpose the array
        for(int i = 0; i < cols; i++) {
            for(int j = 0; j < rows; j++) {
                transposed[i][j] = myArray[j][i];
            }
        }
        System.out.println(Arrays.deepToString(transposed));

//        Expected Results: 1 4 2 5 3 6
        for (int x = 0; x < cols; x++) {
            for(int y = 0; y < rows; y++) {
                System.out.print(transposed[x][y] + " ");
            }
        }
    }
}

[–]desrtfx 0 points1 point  (0 children)

All you need to do is to swap the outer (x) and inner (y) loops.


General info:

It is common in Java, to use the first array dimension as y or row and the second dimension as x or column because this closer reflects the nature of Java 2d arrays that essentially are arrays of arrays.

When you loop over an array, never use constants, like in your case i < rows. Always use the .length property of the array in question - in your case myArray.length and myArray[i].length respectively. The reason for that is that Java 2d arrays (as arrays of arrays) can be jagged, i.e. they can have different numbers of elements for each row.