a | A | |||||
b | B | |||||
c C | ||||||
B | d | |||||
E | e | |||||
Let's say you have the diagonal patch as a-b-c-d-e in above 7*7 matrix
and after rotation it gets as A-B-C-D-E
length = 5
start = [1,2] = a
Now, to rotate it symmetrically, use the symmetric property as
- iterate length/2 times and in every iteration shift the 2 elements, eventually shifting length/2 * 2 = total elements
But How?
Please have a look at following diagram:
length = 5, so total iterations = length/2 = 2
in 1st iteration, shift as shown by bigger arrow
in 2nd iteration, shift as shown by smaller arrow
center element remain as it is.
1) Why length/2 iterations?
=> Idea is we are basically starting with start of diagonal, and by making use of length we deal with the other element of the diagonal e.g. [1,2] = a and [1+len-1, 2+len-1] = [5, 6] = e
So, idea of accessing is 2 elements in ONE iteration is clear.
2) Now, how to re-position these 2 elements for the desired rotation?
=> gap = length - 1
current_element = [i, j]
new_element = [i, j + gap] #just shift right to correct column
current_symmetric_element = [l, m] # l = i + gap, m = j + gap
new_symmetric_element = [l, m - gap] #shift left to correct column
3) The step 2 is for just one element, but we need to slide down for rows, finally it gets as follows:
[i,j] = start_element, length = length of diagonal
[l,m] = end_of_diagonal
gap = length - 1
for x in 0 to length/2:
print i + x, j + (gap - x)
print l - x, j - (gap -x)
if length is odd:
print i + length/2, j + length/2
Python code:
i, j, l = 2, 3, 5
for i1 in range(0, l):
print i + i1, j + i1
print
print
#we need to use symmetricity to rotate i.e. we just need to iterate half the times of length which is l here
#in 1st iteration we will shift the extreme elements and in 2nd remaining 2
#this also works in generic way i.e. iterate half the times of lenght and deal with 2 elemts at a time which in total orders the total elements in diagonal
for x in range(0,l/2):
print i+x, j + (l - 1 - x)
print i+l-1-x, j+l-1-(l-1-x)
if not l%2 == 0:
print i+l/2, j+l/2
No comments:
Post a Comment