Rotate array clockwise

65,439

Solution 1

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;-).

Solution 2

Here's a standard matrix clockwise rotation code:

static int[][] rotateCW(int[][] mat) {
    final int M = mat.length;
    final int N = mat[0].length;
    int[][] ret = new int[N][M];
    for (int r = 0; r < M; r++) {
        for (int c = 0; c < N; c++) {
            ret[c][M-1-r] = mat[r][c];
        }
    }
    return ret;
}

Note a few things:

  • It improves readability to refer to the dimensions of a MxN matrix as M and N
  • It's traditional to use r, c instead of i, j to index row and column of a matrix
  • This is not the most robust implementation:
    • Does not ensure that mat is a valid MxN matrix, M>0, N>0
  • Use an explicit mapping formula instead of extraneous local variables
    • Makes program less complex and more readable

Here's a test harness:

import java.util.Arrays;
//...

static void printMatrix(int[][] mat) {
    System.out.println("Matrix = ");
    for (int[] row : mat) {
        System.out.println(Arrays.toString(row));
    }
}
public static void main(String[] args){
    int[][] mat = {
        { 1, 2, 3 },
        { 4, 5, 6 }
    };
    printMatrix(mat);
    // Matrix = 
    // [1, 2, 3]
    // [4, 5, 6]

    int[][] matCW = rotateCW(mat);
    printMatrix(matCW);
    // Matrix = 
    // [4, 1]
    // [5, 2]
    // [6, 3]
}

Note the use of the for-each loop and java.util.Arrays in printMatrix. You should definitely familiarize yourself with them if you're working with arrays a lot in Java.

Links to Java matrix libraries

If you're working with matrices a lot, you may want to consider using a specialized matrix library instead.

Related questions

Technically, Java has array of arrays. Make sure you understand all the implications.

Solution 3

jj++ is run i*j times, and that can't be good at all.

Try to reset jj in the outer loop.

Solution 4

static int[][] rotateClockwise(int[][] matrix) {
    int rowNum = matrix.length;
    int colNum = matrix[0].length;
    int[][] temp = new int[rowNum][colNum];
    for (int i = 0; i < rowNum; i++) {
        for (int j = 0; j < colNum; j++) {
            temp[i][j] = matrix[rowNum - j - 1][i];
        }
    }
    return temp;
}

Solution 5

Solution for generic objects:

public static <T> T[][] rotateArray90clockwise(Class<T> clas, T[][] array) {

    T[][] target = (T[][]) java.lang.reflect.Array.newInstance(
            clas, array[0].length, array.length);

    for (int i = 0; i < target.length; i++) {
        for (int j = 0; j < target[i].length; j++) {
            target[i][j] = array[(target[i].length - 1) - j][i];
        }
    }

    return target;
}

usage:

rotateArray90clockwise(Some.class,array);
Share:
65,439
user69514
Author by

user69514

Updated on March 29, 2022

Comments

  • user69514
    user69514 about 2 years

    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;
    }
    
    • polygenelubricants
      polygenelubricants almost 14 years
      This is not a matrix rotation. It's a matrix transposition en.wikipedia.org/wiki/Transpose which is a reflection on the main diagonal.
    • Maciej Hehl
      Maciej Hehl almost 14 years
      This just reverses the rows, but jj has to be set to 0 for every i. To rotate exchange i with j in arr[i][j] (and don't forget to set jj to 0
  • Alex Martelli
    Alex Martelli almost 14 years
    @user, you're welcome -- I did suspect I was missing some flipping and/or upside-down vs downside-up for either (or both?-) indices, as I mentioned in the 2nd paragraph;-).
  • Maciej Hehl
    Maciej Hehl almost 14 years
    newArray[i][j] = arr[j][i]; transposes the matrix. It should be newArray[i][length-1-j] = arr[j][i];
  • polygenelubricants
    polygenelubricants almost 14 years
    @MacieJ is correct. See my answer for a more thorough treatment of the problem.
  • Ashwini Kaushik
    Ashwini Kaushik over 7 years
    Very simple logic to rotate the matrix in clockwise or anticlockwise direction
  • Raja Anbazhagan
    Raja Anbazhagan about 7 years
    How do i turn it counter clockwise
  • Greedo
    Greedo over 2 years
    Hi, please add some explaination to your code to help the OP understand it
  • Zoomzoom
    Zoomzoom over 2 years
    What makes this implementation "standard"? Is it published somewhere, or is this code supposed to be so simple that anyone who's not an idiot like me should just be able to figure out quickly?