views:

156

answers:

4

I want a 2d matrix to rotate to the right, it compiles fine but when I try to the run it says that the array index is out of bounds exception. For example I want {{10,20,30},{40,50,60}} to rotate into {{40,10},{50,20},{60,30}}

import java.util.*;
public class Rotate{
   public static int[][] rotate(int[][] m) {
     int [][] rotateM = new int[m[0].length][m.length];
     for (int i= 0; i< m.length; i++){
        for (int j= 0; j< m[0].length; j++){
           rotateM[i][j] = m[j][m.length-i-1];
        }
     }


     return rotateM;
  }
   public static void main(String[]args){
     int[][]m = {{10,20,30},
           {40,50,60}};
     System.out.println(Arrays.toString(rotate(m)));                  

  }

}

A: 

Don't increment using i = i++. Just write i++.

Marcelo Cantos
I've fixed it but now it says that the array index is out of bounds exception.
adam
A: 

Looks like you just had your indexes reversed.

Instead of:

rotateM[i][j] = m[j][m.length-i-1];

You should have written:

rotateM[j][i] = m[m.length-i-1][j];
kurige
A: 

First of all remove that i = i++.

i++ and j++ will suffice, initialize your arrays and you have your logic wrong,

for (int j = 0; j < m[0].Length; j++)
    for (int i = 0; i < m.Length; i++)
         rotateM[j][i] = m[m.Length - i - 1][j];

That is what you need.

Francisco Soto
A: 

Here is a working example:

private int[][] rotateMatrix(int[][] matrix)
{
    int backupH = h;
    int backupW = w;
    w = backupH;
    h = backupW;
    int[][] ret = new int[h][w];
    for (int i = 0; i < h; ++i) {
        for (int j = 0; j < w; ++j) {
            ret[i][j] = matrix[w - j - 1][i];
        }
    }

    return ret;
}

I used this code to rotate my bricks in Tetris.
But I don't know any more if this code rotates to the left or the right...

Martijn Courteaux