Enable Javascript in your browser and then refresh this page, for a much enhanced experience.
First solution in Uncategorized category for Square Spiral by Moff
def create_spiral(n):
size = 2 * n - 1
m = [[0] * size for _ in range(size)]
m[n - 1][n - 1] = 1
for layer in range(1, n):
nums = list(range((2 * layer - 1) ** 2 + 1, (2 * layer + 1) ** 2 + 1))
sides = [nums[i: i + 2 * layer] for i in range(0, len(nums), 2 * layer)]
for i in range(2 * layer):
m[n-layer-1][n-layer+i] = sides[0][i]
m[n-layer+i][n+layer-1] = sides[1][i]
m[n+layer-1][n+layer-2-i] = sides[2][i]
m[n+layer-2-i][n-layer-1] = sides[3][i]
return m
def find_pos(m, x):
for i, row in enumerate(m):
for j, v in enumerate(row):
if v == x:
return i, j
def find_distance(a, z):
m = create_spiral(32)
return sum(abs(x - y) for x, y in zip(find_pos(m, a), find_pos(m, z)))
Aug. 17, 2015