Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
Spiral coord solution in Uncategorized category for Square Spiral by hanpari
def find_distance(first, second):
pos = 1
x = y = 0
spir = dict()
way = loop = 1
loop += 1
# I am just calculating x,y coordinates
# of steps from 1 to n where n is max(first, second)
# to add them into dict spir
# where key is position, ie. steps of spiral.
# When higher number is reached
# the length between position of first and second
# is calculated and returned.
while pos <= max(first, second):
spir[pos] = (x,y)
for i in range(1, loop):
y += way
pos += 1
spir[pos] = (x,y)
for i in range(1, loop):
x += way
pos += 1
spir[pos] = (x,y)
way *= -1
loop += 1
return (abs(spir[second][0] - spir[first][0]) +
abs(spir[second][1] - spir[first][1]))
if __name__ == '__main__':
#These "asserts" using only for self-checking and not necessary for auto-testing
assert find_distance(1, 9) == 2, "First"
assert find_distance(9, 1) == 2, "Reverse First"
assert find_distance(10, 25) == 1, "Neighbours"
assert find_distance(5, 9) == 4, "Diagonal"
assert find_distance(26, 31) == 5, "One row"
assert find_distance(50, 16) == 10, "One more test"
June 18, 2014