I'm trying to rotate a 3*3 matrix clockwise 90 degrees in python. I've identified that element at [ i ][ j ] goes to [ j ][ new_i ]. Here new_i depends upon the previous i, so i made a function for it called circular subtraction.
if i is 0 then new_i is 2
if i is 1 then new_i is 1
if i is 2 then new_i is 0
after execution, it gave me unexpected results.
I've printed everything that is happening in each iteration. I am unable to figure out how some elements are getting replaced with different ones.
'''
1 2 3 7 4 1
4 5 6 rotate 90 degrees 8 5 2
7 8 9 9 6 3
'''
def circular_subtraction(i):
new_i = i
if(i==0):
new_i = 2
elif(i==1):
new_i = 1
elif(i==2):
new_i = 0
return new_i
def rotate_clock(matrix):
new_matrix = matrix
for i in range(len(matrix)):
for j in range(len(matrix)):
new_i = circular_subtraction(i)
new_matrix[j][new_i] = matrix[i][j]
print("New element added from {},{} to {},{} ::: {} to {}".format(i+1,j+1,j+1,new_i+1,matrix[i][j],new_matrix[j][new_i]))
for each_row in new_matrix:
print(each_row)
matrix = [[1,2,3],[4,5,6],[7,8,9]]
print("Length of the matrix : ",len(matrix))
for each_row in matrix:
print(each_row)
print()
matrix = rotate_clock(matrix)
the input matrix was
[1, 2, 3]
[4, 5, 6]
[7, 8, 9]
The expected result was:
[7, 4, 1]
[8, 5, 2]
[9, 6, 3]
Result is:
[7, 4, 1]
[2, 5, 2]
[1, 2, 1]