We use cookies to ensure you have the best browsing experience on our website. Please read our cookie policy for more information about how we use cookies.
One of the idea is by extracting to straps, rotate it, and combine it back as a matrix.
For the last one, combining it back is quite tedious, so I personally prefer to utilize classes (in-place assignments / reference-assignment) so that I dont need to deal the last one (combine it back)
For the strap example, it should be:
matrix (height=5, width=4):
There will be 2 straps:
[1, 5, 9, 13, 17, 18, 19, 20, 16, 12, 8, 4, 3, 2]
and the second one: [6, 10, 14, 15, 11, 7, ]
classValue():def__init__(self,val):self.val=valdefset(self,new_val):self.val=new_valdef__str__(self):returnstr(f"{self.val}")def__repr__(self):returnstr(f"{self.val:2d}")defmatrixRotation(matrix,r):h=len(matrix)w=len(matrix[0])matrix=[#converttoreference-basedvalues[Value(col)forcolinrow]forrowinmatrix]# max number of straps. indexes means strapnum_of_indexes=min(h,w)// 2 forindexinrange(num_of_indexes):extracted=extract(matrix,index)extracted_render=[x.valforxinextracted]r_mod=r%len(extracted_render)foriinrange(len(extracted)):extracted[i].val=extracted_render[i-r_mod]# combine back process. But because we use classes/references, # dont need to do extra complex things here. Just print as usualforrowinmatrix:print(" ".join(map(str,row)))defextract(matrix,dia_index):#extractstraparraysbystrap-indexh=len(matrix)w=len(matrix[0])ret=[]foryinrange(dia_index+0,h-dia_index):#fromtop-lefttobottomret.append(matrix[y][dia_index])forxinrange(dia_index+1,w-dia_index):#frombottom-lefttoright(exceptthefirstitem,alreadyincludedbyfor-loopabove)ret.append(matrix[-dia_index-1][x])foryinrange(h-1-1-dia_index,dia_index-1,-1):#frombottom-righttotop(exceptthefirstitem)ret.append(matrix[y][-dia_index-1])forxinrange(w-1-1-dia_index,dia_index,-1):#fromtop-righttoleft(exceptfirstandlastitem)ret.append(matrix[dia_index][x])returnret
Cookie support is required to access HackerRank
Seems like cookies are disabled on this browser, please enable them to open this website
Matrix Layer Rotation
You are viewing a single comment's thread. Return to all comments →
One of the idea is by extracting to straps, rotate it, and combine it back as a matrix.
For the last one, combining it back is quite tedious, so I personally prefer to utilize classes (in-place assignments / reference-assignment) so that I dont need to deal the last one (combine it back)
For the strap example, it should be: matrix (height=5, width=4):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
There will be 2 straps:
[1, 5, 9, 13, 17, 18, 19, 20, 16, 12, 8, 4, 3, 2]
and the second one:[6, 10, 14, 15, 11, 7, ]