I have a two dimensional array that I need to rotate 90 degrees clockwise, however I keep getting arrayindexoutofbounds…
public int[][] rotateArray(int[][] arr) {
// first change the dimensions vertical length
// for horizontal length and vice versa
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];
jj++;
}
ii++;
}
return newArray;
}
I don’t understand your loops’ logic — shouldn’t it be
Net of whether each index goes up, like
ihere, or down, likejhere (and of whether either or both need to be "flipped" in the assignment, e.g usingarr.length-1-jin lieu of plainjon one side of the=in the assignment;-), sincearrdimensions arearr.lengthbyarr[0].length, and vice versa fornewArray, it seems to me that the first index onarr(second onnewArray) must be the one spanning the range from 0 toarr.length-1included, 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;-).