Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First build spiral matrix, because I wanted to! solution in Clear category for Square Spiral by Sioul
from itertools import cycle
def spiral_matrix(size):
direction = cycle(((-1, 0), (0, 1), (1, 0), (0, -1)))
matrix = [[None] * (size) for _ in range(size)]
x = size // 2 # starting row
y = size // 2 if size % 2 else size // 2 - 1 # starting column
length = 1 # items to put in matrix before changing the direction
number = 1
while number <= size**2:
for _ in range(2): # two changes of direction before augmenting the length
n = next(direction)
for _ in range(length):
if number <= size**2:
matrix[x][y] = number
number += 1
x += n[0] # moving according to
y += n[1] # the direction
length += 1
return matrix
def coordinates(n, m):
""" return the coordinates (x,y) of integer n in the matrix m """
for i, row in enumerate(m):
if n in row:
return i, row.index(n)
def find_distance(first, second):
size = 1
while size**2 < max(first, second):
size += 1
m = spiral_matrix(size)
xf, yf = coordinates(first, m)
xs, ys = coordinates(second, m)
return abs(xf - xs) + abs(yf - ys) # Manhattan distance
Nov. 19, 2019
Comments: