Given a spiral pattern, my job is to write a function that takes certain coordinates and returns the number at these coordinates. For example:
4 < 3 < 2
v ^
5 0 > 1
v
6 > 7 > 8
If the input is (1, -1)
, the function would return 8
.
I am not looking for a code. I am looking for an explanation as to how spiral patterns work as I am relatively new to programming (taking an introductory online course) and I have never come across such a thing. I would like to also understand the algorithm involved.
Again, I do not want any code, as I am looking to solve this myself. I am only requesting an explanation.
Update: I came up with this code which effectively determines the minimum number for the outer square and iterates until the requires coordinates are reached.
def spiral_index(x, y):
small = max(x, y)*2 - 1
min_number = small**2
xpos = max(x, y)
ypos = -max(x, y) + 1
count = min_number
while xpos != x:
xpos -= 1
count += 1
while ypos != y:
ypos += 1
count += 1
return count
However, my online course submission page rejects the code because it takes too long to execute. So I need a quicker method that is beginner-friendly.