Last active
November 5, 2018 13:30
-
-
Save KarthikMAM/bf9f904843504237c5d0d24eb2f484dd to your computer and use it in GitHub Desktop.
Algorithm to rotate an array 'n' times in the anti-clockwise direction
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
| __author__ = "Karthik M A M" | |
| #get the user input | |
| x = [ input().split() for i in range(int(input().split()[0])) ] | |
| c = int(input()) | |
| n, m = len(x), len(x[0]) | |
| #iterate over each ring | |
| for l in range(min(n, m) // 2): | |
| temp = x[l + 1: n - l - 1] | |
| #get ring at level l | |
| z = x[l][l: m - l] | |
| z += [ i[m - l - 1] for i in temp ] | |
| z += x[n - l - 1][l: m - l][::-1] | |
| z += [ i[l] for i in temp ][::-1] | |
| #circular rotation of the list | |
| z = z[c % len(z):] + z[:c % len(z)] | |
| #set the rotated ring at level l | |
| x[l][l: m - l] = [ z.pop(0) for i in range(m - 2 * l) ] | |
| for y in temp: y[m - l - 1] = z.pop(0) | |
| x[n - l - 1][l: m - l] = [ z.pop(0) for i in range(m - 2 * l) ][::-1] | |
| for y in temp: y[l] = z.pop(-1) | |
| #print the result | |
| print(*x, sep='\n', end='\n\n') | |
| #INPUT | |
| """ | |
| 5 6 | |
| 1 2 3 4 5 6 | |
| 7 8 9 0 1 2 | |
| 3 4 5 6 7 8 | |
| 9 0 1 2 3 4 | |
| 5 6 7 8 9 0 | |
| 6 | |
| """ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment