Advertisement
CodingComputing

Spiral Number Pattern

Apr 9th, 2024 (edited)
464
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Python 1.55 KB | None | 0 0
  1. # *Spiral Number Pattern* Solution from @CodingComputing
  2.  
  3. width, height = 5, 5  # supplied parameters
  4.  
  5. # Make a grid of required dimensions
  6. grid = [[None for _ in range(width)] for _ in range(height)]
  7.  
  8. dirs = [ (1,0),   (0,1),   (-1,0),  (0, -1)]
  9. #       0:RIGHT  1:DOWN   2:LEFT    3.UP
  10. # (in clockwise order)
  11.  
  12.  
  13. # Initialize position and direction
  14. x_next, y_next = 0, 0  # Start at top-left of matrix
  15. curr_dir_idx = 0  # Start with moving rightwards
  16.  
  17. for count in range(width * height):  # Iterate
  18.     x, y = x_next, y_next  # Update
  19.     # At this position, fill in the str of numbers,
  20.     # formatted as a 2 digit int (zero padding if required)
  21.     # start from width*height, and decrement each time
  22.     grid[y][x] = f"{width*height - count:02d}"
  23.     # Propose next position
  24.     x_next = x + dirs[curr_dir_idx][0]  # Propose new x based on current direction
  25.     y_next = y + dirs[curr_dir_idx][1]  # Propose new y based on current direction
  26.     # IF there is a problem with the proposed update, cycle through direction
  27.     if not (0<=x_next<width and 0<=y_next<height and not grid[y_next][x_next]):
  28.         curr_dir_idx = (curr_dir_idx + 1)%4  # Turn 90 degrees clockwise
  29.         x_next = x + dirs[curr_dir_idx][0] # New x based on corrected direction
  30.         y_next = y + dirs[curr_dir_idx][1] # New y based on corrected direction
  31. #
  32. # Join grid into a single string and print it
  33. print("\n".join([" ".join(grid[row]) for row in range(height)]))
  34. #
  35. # Output:
  36. # 25 24 23 22 21
  37. # 10 09 08 07 20
  38. # 11 02 01 06 19
  39. # 12 03 04 05 18
  40. # 13 14 15 16 17
  41.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement