It is a program that arranges numerical values in a spiral shape as shown below.
25 10 11 12 13
24 9 2 3 14
23 8 1 4 15
22 7 6 5 16
21 20 19 18 17
I placed 1 in the center and made a round around it to place the numbers.
First place 1 in the center.
1
↓ Next, take one step on top of 1.
2
1
↓ Make a full turn clockwise.
2 3
1
↓ Go down
2 3
1 4
5
↓ Go to the left
2 3
1 4
7 6 5
↓ Go up
9 2 3
8 1 4
7 6 5
Repeat the above steps for the specified size.
A Python script.
spiral.py
# coding: utf-8
import itertools
#Arrange the numbers in a spiral shape
#
#Example)
# 10 11 12 13
# 9 2 3 14
# 8 1 4 15
# 7 6 5
def spiral(n):
N = (-1, 0)
E = ( 0, 1)
S = ( 1, 0)
W = ( 0, -1)
def advance(p, d):
return p[0] + d[0], p[1] + d[1]
path = [(0, 0)]
for size in itertools.count(3, 2):
if len(path) >= n: break
p = path[-1]
p = advance(path[-1], N) #Take one step up
path.append(p)
#Make a full turn clockwise
for d in [E, S, W, N]:
step = size-2 if d == E else size-1
for _ in range(step):
p = advance(p, d)
path.append(p)
display(path[:n])
def display(path):
m = { path[i] : i+1 for i in range(len(path)) }
rs = [p[0] for p in m]
cs = [p[1] for p in m]
minrow, maxrow = min(rs), max(rs)
mincol, maxcol = min(cs), max(cs)
fmt = '%%%ds' % len(str(len(path)))
for r in range(minrow, maxrow+1):
for c in range(mincol, maxcol+1):
if c > mincol:
print(' ', end='')
x = m[r, c] if (r, c) in m else ' '
print(fmt % x, end='')
print()
def main():
while True:
s = input("size> ")
spiral(int(s))
if __name__ == '__main__':
main()
This is the execution result. size>
is the prompt. If you specify a numerical value, that number will be arranged in a spiral shape.
size> 9
9 2 3
8 1 4
7 6 5
size> 25
25 10 11 12 13
24 9 2 3 14
23 8 1 4 15
22 7 6 5 16
21 20 19 18 17
size> 38
26 27 28 29 30 31
25 10 11 12 13 32
24 9 2 3 14 33
23 8 1 4 15 34
22 7 6 5 16 35
21 20 19 18 17 36
38 37
@trsqxyz rewrote it.
Recommended Posts