djbrentoy - 1 year ago 88
Java Question

# How to rotate 3x3 2d array clockwise by n times

These are my loop statements. The first loop displays the non-rotated block while the second loop rotates and displays the 2d array by n(user input) times. My problem is that the 2d array will rotate once but will not rotate the third and following times around. I want my 2d array to rotate 90 degrees clockwise every time it is displayed.

rot = x.nextInt(); //user input for n rotations
//initial block
System.out.println("1");
for(i=0; i<block.length; i++)
{
for(j=0; j<block[i].length; j++)
System.out.print(block[i][j]+"\t");
System.out.println();
}
//rotated block
for(cnt=2; cnt<=rot; cnt++)
{
System.out.println(cnt);
for(i=0; i<block.length; i++){
for(j=block.length-1; j>=0; j--){
newBlock[i][j] = block[j][i];
System.out.print(newBlock[i][j]+"\t");
}
System.out.println();
}
}

Your current rotation code is wrong AFAIK because you are just transposing the array. Doing this twice is effectively a no-op because it leaves the matrix in its original state. It should be intuitive to you that rotating a matrix by 90 degrees twice (i.e. rotating once by 180 degrees) should not, in general, leave the matrix unchanged. Try this rotation code instead:

int dim = block.length;

for (int i=0; i <= (dim - 1)/2; i++) {
for (int j=i; j < dim - i - 1; j++) {
int p1 = block[i][j];
int p2 = block[j][dim-i-1];
int p3 = block[dim-i-1][dim-j-1];
int p4 = block[dim-j-1][i];

block[j][dim-i-1] = p1;
block[dim-i-1][dim-j-1] = p2;
block[dim-j-1][i] = p3;
block[i][j] = p4;
}
}

I adapted this in-place matrix rotation code from this Quora article.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download