Skip to content

Instantly share code, notes, and snippets.

@zjor
Created March 11, 2023 21:31
Show Gist options
  • Save zjor/70528ab9953ec7c88d1cdf0adc77efae to your computer and use it in GitHub Desktop.
Save zjor/70528ab9953ec7c88d1cdf0adc77efae to your computer and use it in GitHub Desktop.
Generates a spiral of numbers in a matrix
RIGHT = (0, 1)
LEFT = (0, -1)
UP = (-1, 0)
DOWN = (1, 0)
def rotate(d):
if d == RIGHT:
return DOWN
elif d == DOWN:
return LEFT
elif d == LEFT:
return UP
else:
return RIGHT
def generate_spiral(n: int):
m = [[0] * n for _ in range(n)]
coordinates = []
i = 1
x = (n // 2 - 1, n // 2 - 1)
m[x[0]][x[1]] = i
direction = RIGHT
coordinates.append(x)
for side in [2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7, 7, 8, 8, 8]:
steps_remaining = side - 1
while steps_remaining > 0:
steps_remaining -= 1
i += 1
x = (x[0] + direction[0], x[1] + direction[1])
m[x[0]][x[1]] = i
coordinates.append(x)
direction = rotate(direction)
return m, coordinates
spiral, _ = generate_spiral(8)
for row in spiral:
print("\t".join(map(str, row)))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment