Reputation: 375
I'm trying to write a function, rotateByX
, that accepts two parameters, a 4x4 matrix and a number that represents the degrees to rotate the matrix. The degrees are 90, 180, 270,360.. and so on. If the entered degree is positive then the matrix rotates to the right clockwise. If it's negative (e.g -90,-180..) then the matrix rotates to the left, counter clockwise. I was able to solve a similar problem, in which I needed only to rotate 90 degrees clockwise. I used this funnction in my code here, and also made another function that rotates 90 degrees counter clockwise. So I rotate the matrix using those two functions, according to the input of degrees.
def rotate90_Counter(m):
return [[m[j][i] for j in range(len(m))] for i in range(len(m[0])-1,-1,-1)]
def rotateByX(m,X):
rotations = (X//90)%4
if X >= 0:
for p in range(rotations):
m= rotate90_clockwise(m)
elif X < 0:
for s in range(rotations):
m= rotate_90_Counter(m)
return m
m = [[1,2,3,4],[5,6,7,8],[9,10,11,12],[13,14,15,16]]
rotateByX(m, -90)
This is currently working only when the input of degrees, X, is positive. So 90, 180, 270.. it rotates beautifuly. But with negative X it rotates to the right (clockwise) rather than to the left.
Upvotes: 0
Views: 561
Reputation: 23144
rotateByX
calculates a number rotations
which is the number of times to rotate clockwise by 90 degrees in order to achieve a rotation by X
degrees clockwise (which is equal to -X
degrees counterclockwise).
So just always rotate clockwise rotations
times. Don't rotate counterclockwise ever. Drop the if X >= 0
/elif X < 0
, all the relevant information about X
is already contained in rotations
.
def rotateByX(m, X):
rotations = (X // 90) % 4
for p in range(rotations):
m = rotate90_clockwise(m)
return m
Upvotes: 0