Skip to content

Instantly share code, notes, and snippets.

@jayrbolton
Created May 6, 2020 02:46
Show Gist options
  • Save jayrbolton/8adb647d4a63e0e46b4790b4acd15e1f to your computer and use it in GitHub Desktop.
Save jayrbolton/8adb647d4a63e0e46b4790b4acd15e1f to your computer and use it in GitHub Desktop.
# Right turn directions
TURN_DIR = {
'u': 'r',
'r': 'd',
'd': 'l',
'l': 'u',
}
# Right turn coordinate math
TURN_FN = {
'u': lambda x, y: (x, y + 1),
'r': lambda x, y: (x + 1, y),
'd': lambda x, y: (x, y - 1),
'l': lambda x, y: (x - 1, y),
}
def spiral(steps):
"""
# `prev` is the previous step's direction
# `dir is a direction, one of:
# - 'r' - right
# - 'l' - left
# - 'd' - down
# - 'u' - up
`pos` is the current coordinate position
`history` is a set of previously visited positions
"""
yield (0, 0)
yield (0, 1)
pos = (0, 1)
dir = 'u'
history = set(("0:0", "0:1"))
for _ in range(steps):
right_dir = TURN_DIR[dir]
# Test the turn to the right
(rightx, righty) = TURN_FN[right_dir](*pos)
right_key = f"{rightx}:{righty}"
if right_key in history:
# We already visited the node to the right, so continue forward
pos = TURN_FN[dir](*pos)
history.add(f"{pos[0]}:{pos[1]}")
else:
# Turn right!
pos = (rightx, righty)
history.add(right_key)
dir = right_dir
yield pos
if __name__ == '__main__':
for pair in spiral(10):
print(pair)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment