javamatrix2048

rotate a N*N Matrix by 9à degrees to right inPlace


i'm trying to make a console 2048 game in Java, i'd like to implement a rotation of the board by 90 degrees to the right, i searched on the web and implemented a function but it's not swapping every rows and colums, could someone please review what i wrote and help me pinpoint the actual error in my code.

public static void rotation90Droite(int [][] vals) {

    int e = vals.length-1;
    int c = e / 2;
    for (int i = 0; i <= c ; i++) {
        for (int j = i; j <e - i; j++) {
            int t   = vals[i][j];


            vals[i][j] = vals[e - j][i];

            vals[e - j][i] = vals[e - i][e - j];

            vals[e - i][e - j] = vals[j][e - i];

            vals[j][e - j] = t;
        }
    }
}
public static void printMatrix(int[][] Matrix) {

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


public static void main(String[] args) {

    int[][] vals = {{1,2,3,4},{5,6,7,8},{9,10,11,12},{13,14,15,16}} ;
    printMatrix(vals);
    System.out.println(" ");
    rotation90Droite(vals);
    printMatrix(vals);

    }
}

This should actually make the first row become the last column, the last column become the last row etc...

what i'm actually getting is :

1 2 3 4  
5 6 7 8 // Starting matrix 
9 10 11 12  
13 14 15 16  

13 9 5 1  
14 3 6 8   // end matrix 
15 11 2 12  
16 12 8 4  

As you can see the last row swaped correctly but so muchs values are not in the right place, i can't find why. Any help will be appreciated thanks you by advance


Solution

  • Geometric problems like this usually have a pattern to how you're accessing the elements of your array. If you read through the indices you're using, the last assignment in your loop doesn't quite match the pattern:

    vals[j][e - j] = t;
    

    should be:

    vals[j][e - i] = t;
    

    Here's a working demo.


    For the future, learning to use a debugger will be an extremely valuable tool for solving these sorts of problems.