frank lowe
frank lowe

Reputation: 29

python inward number spiral going backwards

I am trying to make a spiral that looks like this

21 22 23 24 25
20  7 8  9  10
19  6 1  2  11
18  5 4  3  12
17 16 15 14 13

this is my code and it prints out a matrix but the numbers start on the outside and work in which is the opposite of what I want. How can I change this?

def main():
    spiral = open('spiral.txt', 'r') # open input text file
    dim = int(spiral.readline()) # read first line of text
    num = int(spiral.readline()) # read second line
    spiral.close()
    print(dim)
    if dim % 2 == 0: # check to see if even
        dim += 1 # make odd
        print(dim)
    print(num)
    dx, dy = [0, 1, 0, -1], [1, 0, -1, 0]
    x, y, c = 0, -1, 1
    m = [[0 for i in range(dim)] for j in range(dim)]
    for i in range(dim + dim - 1):
            for j in range((dim + dim - i) // 2):
                    x += dx[i % 4]
                    y += dy[i % 4]
                    m[x][y] = c
                    c += 1
    print(m)
    print('\n'.join([' '.join([str(v) for v in r]) for r in m]))
    print(num)

main()

Upvotes: 0

Views: 426

Answers (1)

zormit
zormit

Reputation: 543

replace

m[x][y] = c

by

m[x][y] = dim**2 + 1 - c

which basically counts backwards. Also you might want to have proper spacing with:

print('\n'.join([' '.join(["{:2}".format(v) for v in r[::-1]]) for r in m]))

Upvotes: 1

Related Questions