Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class MatrixUtilities {
- static int counter;
- static final String TOTAL_ITERATIONS = "\nPerformed %d swaps.";
- static final String SEPARATOR = "\n\n";
- public static void rotateCounter(int[][] a) {
- counter = 0;
- int len = a.length;
- for(int i = 0; i < (len / 2); i++) {
- for(int j = 0; j < len; j++) {
- swap(a, j, i, j, ((len-1) - i));
- counter++;
- }
- }
- for(int i = 0; i < len; i++) {
- for(int j = i; j < len; j++) {
- if(i == j) {
- continue;
- }
- swap(a, i, j, j, i);
- counter++;
- }
- }
- }
- public static void rotate(int[][] a) {
- counter = 0;
- int len = a.length;
- for(int i = 0; i < (len / 2); i++) {
- for(int j = 0; j < len; j++) {
- swap(a, i, j, ((len-1) - i), j);
- counter++;
- }
- }
- for(int i = 0; i < len; i++) {
- for(int j = i; j < len; j++) {
- if(i == j) {
- continue;
- }
- swap(a, i, j, j, i);
- counter++;
- }
- }
- }
- public static void swap(int[][] a, int i, int j, int x, int y) {
- int temp = a[i][j];
- a[i][j] = a[x][y];
- a[x][y] = temp;
- }
- public static void printOut(int[][] a) {
- int len = a.length;
- for(int i = 0; i < len; i++) {
- for(int j = 0; j < len; j++) {
- System.out.print(a[i][j] + " ");
- }
- System.out.println();
- }
- }
- public static void printRotateAndPrint(int[][] a, Rotation r) {
- printOut(a);
- if(r == Rotation.CLOCKWISE){
- rotate(a);
- }
- else {
- rotateCounter(a);
- }
- System.out.println("---ROTATED TO---");
- printOut(a);
- System.out.printf(TOTAL_ITERATIONS, counter);
- }
- public static enum Rotation {
- CLOCKWISE, COUNTER_CLOCKWISE;
- }
- public static void main(String[] args) {
- int[][] a = { {1,2}, {3,4}};
- printRotateAndPrint(a, Rotation.CLOCKWISE);
- System.out.println(SEPARATOR);
- int[][] b = { {1,2,3}, {4,5,6}, {7,8,9}};
- printRotateAndPrint(b, Rotation.CLOCKWISE);
- System.out.println(SEPARATOR);
- int[][] c = { {1,2,3,4}, {5,6,7,8}, {9,10,11,12}, {13,14,15,16} };
- printRotateAndPrint(c, Rotation.CLOCKWISE);
- System.out.println(SEPARATOR);
- int[][] d = { {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}};
- printRotateAndPrint(d, Rotation.CLOCKWISE);
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement