Created
February 7, 2016 22:32
-
-
Save jac1013/febd6a0b8f825a741d41 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/* | |
Input 1: | |
[1,2,3,4] | |
[6,7,8,9] | |
[3,4,5,6] | |
[8,9,3,4] | |
Output 1: | |
[6,1,2,3] | |
[3,4,7,4] | |
[8,5,8,9] | |
[9,3,4,6] | |
Input 2: | |
[1,2,3,4,5] | |
[6,7,8,9,2] | |
[3,4,5,6,7] | |
[8,9,3,4,5] | |
[2,3,5,6,7] | |
Output 2: | |
[6,1,2,3,4] | |
[3,4,7,8,5] | |
[8,9,5,9,2] | |
[2,3,4,6,7] | |
[3,5,6,7,5] | |
*/ | |
public class SquareMatrix { | |
static int[][] even = {{1, 2, 3, 4}, {6, 7, 8, 9}, {3, 4, 5, 6}, {8, 9, 3, 4}}; | |
static int[][] evenResult = {{6, 1, 2, 3}, {3, 4, 7, 4}, {8, 5, 8, 9}, {9, 3, 4, 6}}; | |
static int[][] uneven = {{1, 2, 3, 4, 5}, {6, 7, 8, 9, 2}, {3, 4, 5, 6, 7}, {8, 9, 3, 4, 5}, {2, 3, 5, 6, 7}}; | |
static int[][] unevenResult = {{6, 1, 2, 3, 4}, {3, 4, 7, 8, 5}, {8, 9, 5, 9, 2}, {2, 3, 4, 6, 7}, {3, 5, 6, 7, 5}}; | |
public static void main(String[] args) { | |
compare(resolve(even), evenResult); | |
compare(resolve(uneven), unevenResult); | |
} | |
private static int[][] resolve(int[][] input) { | |
boolean isUneven = (input.length % 2) != 0; | |
int numberOfIterations = input.length / 4; | |
int center = input.length / 2; | |
int[][] result = new int[input.length][input.length]; | |
for (int i = 0; i <= numberOfIterations; i++) { | |
result = rotate(result, input, i); | |
} | |
if (isUneven) { | |
result[center][center] = input[center][center]; | |
} | |
return result; | |
} | |
private static int[][] rotate(int[][] result, int[][] input, int row) { | |
int nextRow = row + 1; | |
int length = input.length; | |
for (int i = row; i < length - nextRow; i++) { | |
result[row][i + 1] = input[row][i]; | |
} | |
for (int i = row; i < length - nextRow; i++) { | |
result[i + 1][length - nextRow] = input[i][length - nextRow]; | |
} | |
for (int i = length - nextRow; i > row; i--) { | |
result[length - nextRow][i - 1] = input[length - nextRow][i]; | |
} | |
for (int i = length - nextRow; i > row; i--) { | |
result[i - 1][row] = input[i][row]; | |
} | |
return result; | |
} | |
private static boolean compare(int[][] result, int[][] expected) { | |
for (int i = 0; i < result.length; i++) { | |
for (int j = 0; j < result.length; j++) { | |
if (result[i][j] != expected[i][j]) { | |
throw new Error(); | |
} | |
} | |
} | |
return true; | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment