# 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]; jj++; } ii++; } return newArray; } `

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

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.

• JAMA: http://math.nist.gov/javanumerics/jama/
• UJMP: http://www.ujmp.org/

### Related questions

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

• Performance comparison of array of arrays vs multidimensional arrays
• Java `Arrays.equals()` returns `false` for two dimensional arrays.

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

Try to reset jj in the outer loop.

`public class RotateMatrix {`

``` static int index_of_rows; static int index_of_columns; static int number_of_rows; static int number_of_columns; public static void main(String[] args) { int[][] matrix={{1,2,3,4,5}, {6,7,8,9,10}, {11,12,13,14,15}, {16,17,18,19,20}, {21,22,23,24,25}}; index_of_rows = matrix.length -1; index_of_columns = matrix[0].length -1; number_of_rows = matrix.length; number_of_columns = matrix[0].length; RotateMatrix rm = new RotateMatrix(); rm.printGrid(matrix);//before rotation rm.rotate360CW(matrix,rm); } public int[][] rotate90CW(int[][] matrix, RotateMatrix rm) { int[][] newMatrix = new int[number_of_rows][number_of_columns]; int totalNumber = (number_of_rows) * (number_of_columns); int[] intArray = createSingleArray(matrix,totalNumber); int a =0; for(int c=number_of_columns; c>=0; c--) { for(int r=0; r<=number_of_rows; r++) { newMatrix[r][c] = intArray[a]; a++; } } rm.printGrid(newMatrix); return newMatrix; } public int[] createSingleArray(int[][] matrix, int totalNumber) { int a=0; int[] intArray = new int[totalNumber]; for(int b=0;b<=index_of_rows; b++) { for(int c=0; c<=index_of_columns;c++) { intArray[a] = matrix[b][c]; a++; } } return intArray; } public void printGrid(int[][] matrix) { StringBuilder sb = new StringBuilder("--------------------------"); for(int i =0; i<=index_of_rows; i++) { System.out.println(sb.toString());//print each row sb.delete(0, sb.length());//Then clear the row and build the next for(int j=0; j<=index_of_columns;j++) { sb.append(matrix[i][j]+","); } } System.out.println(sb.toString()); } public int[][] rotate180CW(int[][] matrix, RotateMatrix rm) { return rm.rotate90CW(rm.rotate90CW(matrix, rm), rm); } public int[][] rotate270CW(int[][] matrix, RotateMatrix rm) { return rm.rotate90CW(rm.rotate90CW(rm.rotate90CW(matrix, rm), rm),rm); } public int[][] rotate360CW(int[][] matrix, RotateMatrix rm) { return rm.rotate90CW(rm.rotate90CW(rm.rotate90CW(rm.rotate90CW(matrix, rm), rm),rm),rm); } ```

```} ```

Category:java Views:0 Time:2010-05-10

## Related post

• Searching in an sorted and rotated array 2011-01-23

While preparing for tech interview I stumbled upon this interesting question: You've been given an array that is sorted and then rotated. example Let arr = [1,2,3,4,5] which is sorted and then rotated say twice to the right to give [4,5,1,2,3] Now ho

• Find smallest number in Sorted Rotatable Array 2011-12-16

I came across this question in one Interview. Please help me in getting the solution. Question is: You have sorted rotatable array, i. e. the array contains elements which are sorted and it can be rotated circularly, like if the elements in array are

• screen rotated counter clockwise 2012-05-08

My screen rotated counter clockwise, i tried ctrl+alt+arrow keys still didnt work, can someone help? --------------Solutions------------- If Pressing CTRL + ALT + the Up Arrow Key didn't work try right click on the desktop, selectGraphic Options | Ro

• Rotate image clockwise or anticlockwise inside a div using javascript 2009-06-09

HI, Is there a way by which I can rotate an image inside a div clockwise or anticlockwise. I have a main fixed width div[overflow set to hidden] with images loaded from database. There is a scroll bar for showing the images inside the div. When image

• j2me - Rotate array of 2d points in 45 degree increments 2009-03-12

I'm working on a roguelike style cellphone game that operates on a grid. Attacks/Items in this game operate by targeting tiles in a pattern relative to the user. The paturn is usually relative to the direction the user is aiming in as well, For insta

• Rotating array differently 2010-10-23

hey, I need to rotate a 2d array in such way : 4X4--> Input Output 1 2 3 4 5 1 2 3 5 6 7 8 1 2 6 4 1 2 3 4 5 3 7 8 5 6 7 8 6 7 8 4 or for odd 5X5--> Input Output 1 2 3 4 5 6 1 2 3 4 6 7 8 9 10 1 2 7 8 5 1 2 3 4 5 6 7 3 9 10 6 7 8 9 10 1 8 9 4 5

• how To detect that cgaffinetransformrotate method is rotating the clockwise or anticlockwise? 2011-02-09

I need to figure Out that thorough the Cgaffinetransformrrotate I am rotating the view towards the clockwise or anticlockwise. how it is possible? --------------Solutions------------- YourView.transform = CGAffineTransformMakeRotation( positive value

• XCode rotate uibutton clockwise 2011-02-19

I want to rotate an UIButton at 180 degrees clockwise. But it always rotate counterclockwise. This is how I tried: CGContextRef context = UIGraphicsGetCurrentContext(); [UIView beginAnimations:nil context:context]; [UIView setAnimationCurve:UIViewAni

• Rotate array of bytes 2011-09-02

I have an array of bytes that make up a 256 x 256 8 bit gray scale image. I need to rotate (or arrange) the array of bytes such that when the image is recreated from the array it is rotated by 90, 180 and 270 degrees. I could create a memory stream o

• Rotate Image Clockwise using LibGDX 2012-02-25

How can we rotate a Image Clockwise using LibGDX? what i am looking is when a image is loaded,suppose a star, i need to rotate it from beginning of screen to end of the screen horizontally, with star rotating,how can i do that in libgdx? ------------

• Rebind a rotated array with knockoutjs 2013-06-27

I want to rotate back and forth (carrousel) an array on pressing the according buttons. The below code does that exactly. Now I asked my self is this the correct way it should be done. I mean the way how I rebind the result from the rotation function

• sort-of-solved: printing landscape page...rotate options (clockwise/counterclockwise) 2013-12-30

Hello, I have a multi-page document, that using section breaks, has both portrait and landscaped pages. I need to print a lot of copies, that will be inserted in three ring binders. I want to print on 3-hole punched paper (to save a lot of labour). W

• Google Chrome rotates anti-clockwise but should be clockwise 2014-01-09

I have this CSS that I use for a triangle to be used for opening/closing a properties item, when the I click on the triangle I apply the "is-active" class and the triangle goes from pointing to the left to pointing down in a clockwise direction (work

• jQuery: rotate image clockwise/counter-clockwise in 90 degree increments? 2011-02-15

I'm looking for a jQuery plugin that will allow me to rotate an image with smooth animation as it transitions from one angle to another. Can anyone suggest a plugin if there is such a plugin? --------------Solutions------------- Maybe you can look at

• Rotating image clockwise and anticlock wise using Translate Transform in c# 2011-11-01

I'm using the following code to rotate an image by an angle taking the center point as the origin. private Bitmap rotateImage(Bitmap b, float angle) { Bitmap returnBitmap = new Bitmap(b.Width, b.Height); Graphics g = Graphics.FromImage(returnBitmap);

• Rotate array by arbitrary step size without creating second array 2012-03-09

So for a step size of 1, I want the array: {1, 2, 3, 4} To become: {4, 1, 2, 3} And for a step of size 2 the result will be: {3, 4, 1, 2} This is the code I'm using now: private static int[] shiftArray(int[] array, int stepSize) { if (stepSize == 0)

• why am i not allowed to rotate pictures clockwise 2013-04-25

the photos where all taken on my iphone 4s on the same day and even pics from the same time bracket will be allowed to rotate yet some have a warning message thatpops up and say not allowed see properties might be read only file which they arnt. So h

• How do I get a toolbar that includes UNDO and ROTATE photos clockwise or anti-clockwise? 2014-04-15

The default toolbar does NOT include the above operations I need to implement. I believe the STANDARD TOOLBAR does. So how do I go about installing the STANDARD TOOLBAR and making it my DEFAULT TOOLBAR? --------------Solutions------------- Hi, Thank

• How do you rotate a two dimensional array? 2008-09-03

Inspired by Raymond Chen's post, say you have a 4x4 two dimensional array, write a function that rotates it 90 degrees. Raymond links to a solution in pseudo code, but I'd like to see some real world stuff. [1][2][3][4] [5][6][7][8] [9][0][1][2] [3][