Jay Shah
Jay Shah

Reputation: 742

Rotate elements of matrix in counter clockwise direction

How can we rotate 5X5 matrix in conuter clock wise direction by 45 degree?

Input will be like this:

00100
00100
11111
00100
00100

And output should be like this:

10001
01010
00100
01010
10001

What I have done so far is I have read elements of 5X5 array now I have stuck with the logic of rotation.

My code is as below:

import java.awt.Point;
import java.util.Scanner;

public class RotateMatrix {
  public static void main(String a[]) {
    int[][] original = new int[5][5];
    int[][] rotate = new int[5][5];
    String helper[] = new String[5];
    Scanner sc = new Scanner(System.in);
    for (int i = 0; i < 5; i++) {
      helper[i] = sc.next();
    }
    for (int i = 0; i < 5; i++) {
      for (int j = 0; j < 5; j++) {
        original[i][j] = Integer.parseInt(String.valueOf(helper[i].charAt(j)));
      }
    }
  }
}

Upvotes: 0

Views: 574

Answers (1)

Joni
Joni

Reputation: 111379

Assuming "rotating by 45 degrees" means that entries on the outer border should stay on the outer border, what you need to do is:

  • rotate the outer 5x5 ring by 2 positions
  • rotate the inner 3x3 ring by 1 position

The outer 5x5 ring rotates like this:

01234      23456
F   5      1   7
E   6  =>  0   8
D   7      F   9
CBA98      EDCBA

You can do this rotation with a for loop. This one does top, right and bottom sides as an example:

for (int i = 0; i < 5; i++) {
  if (i < 3) {
    rotate[0][i] = original[0][i+2]; // TOP
    rotate[i][4] = original[i+2][4]; // RIGHT
    rotate[4][4-i] = original[4][4-(i+2)]; // BOTTOM
  } else {
    rotate[0][i] = original[i-2][4]; // TOP
    rotate[i][4] = original[4][4-(i-2)]; // RIGHT
    rotate[4][4-i] = original[4-(i-2)][0]; // BOTTOM
  }
}

Once you add the code to fill the left side of rotate and the code to rotate the inner 3x3 ring you're done!

This may amount to quite a lot of code. You may want to make a method that rotates an arbitrary ring of the matrix by 1. Then you would call this method 3 times: once on the inner ring, and twice on the outer ring so it rotates by 2.

Upvotes: 1

Related Questions