Skip to content

Instantly share code, notes, and snippets.

@louisswarren
Last active August 8, 2020 01:49
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save louisswarren/ad4ade5c27b8616a2d466d31306bc960 to your computer and use it in GitHub Desktop.
Save louisswarren/ad4ade5c27b8616a2d466d31306bc960 to your computer and use it in GitHub Desktop.
Spirals of numbers
class Turtle:
directions = [( 0, 1),
(-1, 0),
( 0, -1),
( 1, 0)]
def __init__(self, x=0, y=0, d=0, boundary=lambda x, y: True):
self.x = x
self.y = y
self.d = d
self.boundary = boundary
self.tasks = []
def do_step(self):
self.x += Turtle.directions[self.d][0]
self.y += Turtle.directions[self.d][1]
return self.x, self.y
def do_left(self):
self.d = (self.d + 1) % 4
def do_right(self):
self.d = (self.d - 1) % 4
def add_step(self):
self.tasks.append(self.do_step)
def add_steps(self, n):
for _ in range(n):
self.add_step()
def add_left(self):
self.tasks.append(self.do_left)
def add_right(self):
self.tasks.append(self.do_right)
def __iter__(self):
while self.boundary(self.x, self.y):
yield self.x, self.y
if not self.tasks:
return
while not self.tasks.pop(0)():
if not self.tasks:
return
def spiral_grid(n):
grid = [[None for _ in range(n)] for _ in range(n)]
x, y = n // 2, (n + 1) // 2 - 1
t = Turtle(x, y, 0, lambda x, y: 0 <= x < n and 0 <= y < n)
for dist in range(1, n + 1):
t.add_steps(dist)
t.add_left()
t.add_steps(dist)
t.add_left()
for i, pos in enumerate(t):
grid[pos[0]][pos[1]] = i + 1
return grid
def print_spiral(n, sep='\t'):
for line in spiral_grid(n):
print(sep.join(map(str, line)))
if __name__ == '__main__':
for n in range(1, 10):
print_spiral(n)
print()
1
4 3
1 2
5 4 3
6 1 2
7 8 9
16 15 14 13
5 4 3 12
6 1 2 11
7 8 9 10
17 16 15 14 13
18 5 4 3 12
19 6 1 2 11
20 7 8 9 10
21 22 23 24 25
36 35 34 33 32 31
17 16 15 14 13 30
18 5 4 3 12 29
19 6 1 2 11 28
20 7 8 9 10 27
21 22 23 24 25 26
37 36 35 34 33 32 31
38 17 16 15 14 13 30
39 18 5 4 3 12 29
40 19 6 1 2 11 28
41 20 7 8 9 10 27
42 21 22 23 24 25 26
43 44 45 46 47 48 49
64 63 62 61 60 59 58 57
37 36 35 34 33 32 31 56
38 17 16 15 14 13 30 55
39 18 5 4 3 12 29 54
40 19 6 1 2 11 28 53
41 20 7 8 9 10 27 52
42 21 22 23 24 25 26 51
43 44 45 46 47 48 49 50
65 64 63 62 61 60 59 58 57
66 37 36 35 34 33 32 31 56
67 38 17 16 15 14 13 30 55
68 39 18 5 4 3 12 29 54
69 40 19 6 1 2 11 28 53
70 41 20 7 8 9 10 27 52
71 42 21 22 23 24 25 26 51
72 43 44 45 46 47 48 49 50
73 74 75 76 77 78 79 80 81
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment