How do I get this 2D Array to rotate to the right 90 degrees?

柔情痞子 提交于 2019-12-02 06:26:10

问题


So I have a 2D array, and it is supposed to rotate to the right 90 degrees, but instead it rotates to the left. Really can't figure out why

public class CrackCode16 {

public static void main (String args[]){
    int [] [] oldarray = new int [3][3];

    int value = 1;

    for (int i = 0; i < 3; i++){
        for (int j =0; j<3; j++){
            oldarray[i][j] = value;
            value++;
        }
    }


    for (int i = 0; i < 3; i++){
        for (int j =0; j<3; j++){
            System.out.print(oldarray[i][j] + "\t");
        }
        System.out.println("");
    }


    oldarray = rotate(oldarray, 3);


    System.out.println("");
    for (int i = 0; i < 3; i++){
        for (int j =0; j<3; j++){
            System.out.print(oldarray[i][j] + "\t");
        }
        System.out.println("");
    }

}

public static int [][] rotate (int [][] passedIn, int n){

    int [][] newarray = new int [n][n];

    for (int i = 0; i < n; i++){
        for (int j =0; j<n; j++){
            newarray[i][j] = passedIn [j][n-1-i];
        }
    }   

    return newarray;
}

}

Output:

1 2 3
4 5 6
7 8 9

3 6 9
2 5 8
1 4 7


回答1:


newArray[i][j] = passedIn [n-1-j][i];

instead of

newarray[i][j] = passedIn [j][n-1-i];

Additionally, when working with Java8, you might consider using a Stream to print your array:

Stream.of(oldarray).forEach(e -> System.out.println(Arrays.toString(e)));


来源:https://stackoverflow.com/questions/22974924/how-do-i-get-this-2d-array-to-rotate-to-the-right-90-degrees

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!