Created
August 30, 2019 17:07
-
-
Save indranil32/02e64d4093d368c588a4c1ea0795a2ab to your computer and use it in GitHub Desktop.
Square Matrix Rotation
This file contains 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
def matrix = [[ 1, 2, 3, 4, 17], | |
[ 5, 6, 7, 8, 18], | |
[ 9,10,11,12, 19], | |
[13,14,15,16, 20], | |
[21,22,23,24, 25]] | |
/* Output | |
[21, 13, 9, 5, 1] | |
[22, 14, 10, 6, 2] | |
[23, 15, 11, 7, 3] | |
[24, 16, 12, 8, 4] | |
[25, 20, 19, 18, 17] | |
*/ | |
def print2D(arr, n) { | |
for (int i = 0 ; i < n ; i++){ | |
println arr.get(i) | |
} | |
println "" | |
} | |
def rotate(matrix, n) { | |
for (int layer = 0 ; layer < n/2 ; layer++) { // 123 | |
int first = layer | |
int last = n - layer - 1 | |
for (int i = first ; i <last; i++) { | |
int offset = i-first | |
// save top | |
int top = matrix[first][i] // 1 2 | |
// bottom -> top | |
matrix[first][i] = matrix[last-offset][first] // 1 -> 13 2 -> 9 | |
// bottom right -> bottom left | |
matrix[last-offset][first] = matrix[last][last-offset] // 13 -> 16 9 -> 15 | |
// top left -> bottom left | |
matrix[last][last-offset] = matrix[i][last] // 16 -> 4 8 -> 15 | |
// top left -> top right | |
matrix[i][last] = top // 4 -> 1 | |
print2D(matrix, n) | |
} | |
println "Next layer" | |
} | |
} | |
rotate(matrix, 5) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment