user69514 user69514 - 9 months ago 38
Java Question

Rotate array clockwise

I have a two dimensional array that I need to rotate 90 degrees clockwise, however I keep getting arrayindexoutofbounds...

public int[][] rorateArray(int[][] arr){

//first change the dimensions vertical length for horizontal length
//and viceversa
int[][] newArray = new int[arr[0].length][arr.length];

//invert values 90 degrees clockwise by starting from button of
//array to top and from left to right
int ii = 0;
int jj = 0;
for(int i=0; i<arr[0].length; i++){
for(int j=arr.length-1; j>=0; j--){
newArray[ii][jj] = arr[i][j];


return newArray;

Answer Source

I don't understand your loops' logic -- shouldn't it be

   for(int i=0; i<arr[0].length; i++){
        for(int j=arr.length-1; j>=0; j--){
            newArray[i][j] = arr[j][i];

Net of whether each index goes up, like i here, or down, like j here (and of whether either or both need to be "flipped" in the assignment, e.g using arr.length-1-j in lieu of plain j on one side of the = in the assignment;-), since arr dimensions are arr.length by arr[0].length, and vice versa for newArray, it seems to me that the first index on arr (second on newArray) must be the one spanning the range from 0 to arr.length-1 included, and the other range for the other index.

This is a kind of "basic dimensional analysis" (except that "dimension" is used in a different sense than normally goes with "dimensional analysis" which refers to physical dimensions, i.e., time, mass, length, &c;-). The issue of "flipping" and having each loop go up or down depend on visualizing exactly what you mean and I'm not the greatest "mental visualizer" so I think, in real life, I'd try the various variants of this "axis transposition" until I hit the one that's meant;-).