Rotating a specific area of an array

Viewed 52

I have an NxN matrix and I want to pick a specific part of this matrix and rotate that area by 90 degrees clockwise. I have to specify this rotation under these conditions:

  • (a, b) position as upper left corner,
  • (a + c, b + c) position as lower right corner, and
  • whose side length is c + 1.

So, when I give a=2, b=3, and c=3, the output will be like this:

example

Code:

import numpy as np
N = int(input())
S = int(input())
arr = np.array(range(0,N*N))
arr.shape = N,N
for i in range(S):
    a,b,c = [int(x) for x in input().split()]
arr[a:a+c+1,b:b+c+1] = np.rot90(arr[a:a+c+1,b:b+c+1], axes=(1,0))
print(arr);
1 Answers

A 90-degree clockwise rotation corresponds to a vertical flip followed by a transpose. So:

def rotate_clockwise(x):
    return x[::-1].T

To use it on a particular region:

arr[a:a+s, b:b+s] = rotate_clockwise(arr[a:a+s, b:b+s])

In your case, s = c + 2.


EDIT: Perhaps even better is to use np.rot90:

def rotate_clockwise(x):
    return np.rot90(x, 3)
Related