Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # *Spiral of Numbers Pattern* by @CodingComputing
- rows, cols = 5, 5 # parameters
- # Initialization
- size = rows*cols
- matrix = [[None for _ in range(cols)] for _ in range(rows)]
- count = 0 # How many numbers are allocated?
- # Specify movement directions in clockwise order
- dirs = [ (1,0), (0,1), (-1,0), (0, -1)]
- # 0:RIGHT 1:DOWN 2:LEFT 3.UP (in clockwise order)
- # Initialize position and direction
- x_next, y_next = 0, 0 # Start at top-left of matrix
- curr_dir = 0 # Start with moving rightwards
- # Iterate n over decreasing numbers
- for n in range(size, 0, -1):
- x, y = x_next, y_next # Update position
- matrix[y][x] = f"{n:02}" # Fill in the number after converting to zero padded str
- x_next = x + dirs[curr_dir][0] # Propose new x based on current direction
- y_next = y + dirs[curr_dir][1] # Propose new y based on current direction
- # IF there is a problem with the proposed update, cycle through direction
- if not (0<=x_next<rows and 0<=y_next<cols and not matrix[y_next][x_next]):
- curr_dir = (curr_dir + 1)%4 # Turn 90 degrees clockwise
- x_next = x + dirs[curr_dir][0] # New x based on corrected direction
- y_next = y + dirs[curr_dir][1] # New y based on corrected direction
- # Join matrix into a single string and print it
- print("\n".join([" ".join(matrix[row]) for row in range(rows)]))
Advertisement
Add Comment
Please, Sign In to add comment