Skip to content

Instantly share code, notes, and snippets.

@JosephCatrambone
Last active March 4, 2024 06:23
Show Gist options
  • Save JosephCatrambone/ca6ca668364462bb9a3909d7b09877e6 to your computer and use it in GitHub Desktop.
Save JosephCatrambone/ca6ca668364462bb9a3909d7b09877e6 to your computer and use it in GitHub Desktop.
Discrete Grid Spiral Iterator
def square_iterator(x: int, y: int):
"""Generate all the points on a square 2d lattice, spiraling out from the center. Modified from a solution by Nikita Rybak. https://stackoverflow.com/a/3706260"""
dx = 1
dy = 0
segment_length = 1
leg_iterations = 0
while True:
x += dx
y += dy
yield((x, y))
leg_iterations += 1
if leg_iterations >= segment_length:
leg_iterations = 0
# Rotate our direction by 90 degrees, and when we're back to dx == 0 (on the flat side), bump the segment_length by 1.
tmp = dy
dy = -dx
dx = tmp
if dy == 0:
segment_length += 1
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment