CodingComputing

Spiral of Numbers

Jun 13th, 2024
521
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.36 KB | None | 0 0
  1. # *Spiral of Numbers Pattern* by @CodingComputing
  2.  
  3. rows, cols = 5, 5  # parameters
  4.  
  5. # Initialization
  6. size = rows*cols
  7. matrix = [[None for _ in range(cols)] for _ in range(rows)]
  8.  
  9. count = 0  # How many numbers are allocated?
  10.  
  11. # Specify movement directions in clockwise order
  12. dirs = [ (1,0),   (0,1),   (-1,0),  (0, -1)]
  13. #       0:RIGHT  1:DOWN   2:LEFT    3.UP      (in clockwise order)
  14.  
  15. # Initialize position and direction
  16. x_next, y_next = 0, 0  # Start at top-left of matrix
  17. curr_dir = 0  # Start with moving rightwards
  18.  
  19. # Iterate n over decreasing numbers
  20. for n in range(size, 0, -1):
  21.     x, y = x_next, y_next  # Update position
  22.     matrix[y][x] = f"{n:02}" # Fill in the number after converting to zero padded str
  23.     x_next = x + dirs[curr_dir][0]  # Propose new x based on current direction
  24.     y_next = y + dirs[curr_dir][1]  # Propose new y based on current direction
  25.     # IF there is a problem with the proposed update, cycle through direction
  26.     if not (0<=x_next<rows and 0<=y_next<cols and not matrix[y_next][x_next]):
  27.         curr_dir = (curr_dir + 1)%4  # Turn 90 degrees clockwise
  28.         x_next = x + dirs[curr_dir][0] # New x based on corrected direction
  29.         y_next = y + dirs[curr_dir][1] # New y based on corrected direction
  30.  
  31. # Join matrix into a single string and print it
  32. print("\n".join([" ".join(matrix[row]) for row in range(rows)]))
Advertisement
Add Comment
Please, Sign In to add comment