Skip to content

Instantly share code, notes, and snippets.

@hughdbrown
Last active May 2, 2024 17:52
Show Gist options
  • Save hughdbrown/5c13e1338a7d88a2bc9bd990fbd7e4a3 to your computer and use it in GitHub Desktop.
Save hughdbrown/5c13e1338a7d88a2bc9bd990fbd7e4a3 to your computer and use it in GitHub Desktop.
Code to write spiral of integers in a square
from itertools import cycle
def spiral(n):
matrix = [[0] * n for _ in range(n)]
x, y = 0, 0
x0, y0, xn, yn = 0, 0, n, n
directions = cycle([
(1, 0, (0, 0, 1, 0)),
(0, 1, (0, -1, 0, 0)),
(-1, 0, (0, 0, 0, -1)),
(0, -1, (1, 0, 0, 0)),
])
delta_x, delta_y, delta = next(directions)
for i in range(1, n * n + 1):
matrix[y][x] = i
if not (x0 <= (x + delta_x) < xn) or not (y0 <= (y + delta_y) < yn):
x0 += delta[0]
xn += delta[1]
y0 += delta[2]
yn += delta[3]
delta_x, delta_y, delta = next(directions)
x += delta_x
y += delta_y
for row in matrix:
print(" ".join([f"{item:03}" for item in row]))
if __name__ == '__main__':
spiral(10)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment