Arrange the numbers in a spiral shape

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

Creation policy

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.

program

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()

Execution result

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

environment

Postscript

@trsqxyz rewrote it.

Recommended Posts

Arrange the numbers in a spiral shape
Is there a bias in the numbers that appear in the Fibonacci numbers?
Spiral book in Python! Python with a spiral book! (Chapter 14 ~)
Write the test in a python docstring
Cut out A4 print in the image
Change the list in a for statement
Run the Python interpreter in a script
[Python] Get the files in a folder with Python
Use the latest pip in a virtualenv environment
Get the caller of a function in Python
Make a copy of the list in Python
Find the number of days in a month
Get only the subclass elements in a list
Determine the numbers in the image taken with the webcam
You walk in a spiral in a world where the walls of the cross rise (simulation)
Set a fixed IP in the Linux environment
Output in the form of a python array
How to count numbers in a specific range
CCC: coding crash course (4) Make the numbers appearing in pi 3.141562 .... into a histogram
Check if the string is a number in python
Get the file name in a folder using glob
Register a task in cron for the first time
Write a log-scale histogram on the x-axis in python
Create a shape on the trajectory of an object
What does the last () in a function mean in Python?
Clip shape in reportlab
dict in dict Makes a dict a dict
Define a task to set the fabric env in YAML
[Sublime Text 2] Always execute a specific file in the project
A note on the default behavior of collate_fn in PyTorch
Save the pystan model and results in a pickle file
A memorandum to register the library written in Hy in PyPI
Find out the apparent width of a string in python
I tried the super-resolution algorithm "PULSE" in a Windows environment
Create a local scope in Python without polluting the namespace
How to use the __call__ method in a Python class
Change the standard output destination to a file in Python
Note 2 for embedding the scripting language in a bash script
Put the lists together in pandas to make a DataFrame
How to generate a query using the IN operator in Django
[Note] Import of a file in the parent directory in Python
How to get the last (last) value in a list in Python
To write a test in Go, first design the interface
Create a new list by combining duplicate elements in the list
Find the eigenvalues of a real symmetric matrix in Python
[Golang] A program that determines the turn with random numbers
I wrote a script that splits the image in two
Is there a secret to the frequency of pi numbers?