Johannes Zahn
Johannes Zahn

Reputation: 13

Switch Rows and Columns 2d Array

I want to swap Columns and Rows in a 2D array.

My problem is that I want the Variable "oldField" to save the oldField. The Variable I think is Pointing on the same Object as newField and so it get´s changed even tho I dont want that.

Id like to know how I can save the Variable oldField independent

public int[][] swapMatrix(int[][] pField) { // swaps the rows and columns in
                                            // a Field
    int[][] oldField = pField.clone();
    int[][] newField = pField.clone();
    for (int i = 0; i < newField.length; i++) {
        for (int j = (newField.length - 1); j >= 0; j--) {
            newField[i][(newField.length - 1) - j] = oldField[j][i];
        }
    }
    return newField;

}

Upvotes: 0

Views: 2584

Answers (2)

Jose Zevallos
Jose Zevallos

Reputation: 725

this code solves your problem:

public class SwapRowsAndColumns {

    public static void main(String[] args) {

        int[][] someMatrix = new int[2][3];

        someMatrix[0][0] = 1;
        someMatrix[0][1] = 2;
        someMatrix[0][2] = 3;

        someMatrix[1][0] = 4;
        someMatrix[1][1] = 5;
        someMatrix[1][2] = 6;

        printMatrix(someMatrix);
        int[][] invertedMatrix = swapMatrix(someMatrix);
        printMatrix(invertedMatrix);

    }

    private static int[][] swapMatrix(int[][] pField) {

        int originalTotalRows = pField.length;
        int originalTotalColumns = pField[0].length;

        int[][] newMatrix = new int[originalTotalColumns][originalTotalRows];

        for(int i=0; i< originalTotalRows; i++){
            for(int j=0; j < originalTotalColumns; j++){
                newMatrix[j][i] = pField[i][j];
            }
        }
        return newMatrix;
    }

    private static void printMatrix(int[][] matrix){
        int totalRows = matrix.length;
        int totalColumns = matrix[0].length;

        for(int i=0; i< totalRows; i++){
            for(int j=0; j< totalColumns; j++){
                System.out.print(matrix[i][j] + " ");
            }
            System.out.println("");
        }
    }
}

Upvotes: 1

gati sahu
gati sahu

Reputation: 2641

When you copy in 1-D array with primitive value like int then the new array and content copy to it and there is no reference.

 int row1[] = {0,1,2,3};
    int row2[] =  row1.clone();
    row2[0] = 10;
    System.out.println(row1[0] == row2[0]); // prints false

but for 2-D array the content is object and clone method only do shallow copy not create new content if object is there .For your requirement you need to do deep copy.

int table1[][]={{0,1,2,3},{11,12,13,14}};
    int table2[][] = table1.clone();
    table2[0][0] = 100;
    System.out.println(table1[0][0] == table2[0][0]); //prints true

Upvotes: 1

Related Questions