Skip to content

Instantly share code, notes, and snippets.

@boukeversteegh
Created February 21, 2013 17:31
Show Gist options
  • Save boukeversteegh/5006531 to your computer and use it in GitHub Desktop.
Save boukeversteegh/5006531 to your computer and use it in GitHub Desktop.
# Given a position (x,y), returns next position in a grid spiral.
def next(pos):
x, y = pos
top = False
right = False
bottom = False
left = False
horizontal = abs(x) <= abs(y)
vertical = abs(y) <= abs(x)
if y < 0 and horizontal:
top = True
if y > 0 and horizontal:
bottom = True
if x < 0 and vertical:
left = True
if x > 0 and vertical:
right = True
if top:
x+=1
elif left:
y-=1
elif bottom:
x-=1
elif right:
y+=1
return (x, y)
if __name__ == '__main__':
pos = (0, 0)
assertvalues = [
(1,0),
(1,1),
(0,1),
(-1,1),
(-1,0),
(-1,-1),
(0,-1),
(1,-1),
(2,-1),
(2,0),
(2,1),
(2,2),
(1,2),
(0,2),
(-1,2),
(-2, 2),
(-2,1),
(-2,0),
(-2,-1),
(-2,-2),
(-1, -2),
(0, -2),
(1, -2),
(2, -2),
(3, -2)
]
values = [pos]
for i in range(len(assertvalues)):
pos = next(pos)
values.append(pos)
for assertvalue, value in zip(assertvalues, values):
print str(value).ljust(7), "\t", str(assertvalue).ljust(7), "\t", str(assertvalue==value)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment