Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- # *Spiral Number Pattern* Solution from @CodingComputing
- width, height = 5, 5 # supplied parameters
- # Make a grid of required dimensions
- grid = [[None for _ in range(width)] for _ in range(height)]
- 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_idx = 0 # Start with moving rightwards
- for count in range(width * height): # Iterate
- x, y = x_next, y_next # Update
- # At this position, fill in the str of numbers,
- # formatted as a 2 digit int (zero padding if required)
- # start from width*height, and decrement each time
- grid[y][x] = f"{width*height - count:02d}"
- # Propose next position
- x_next = x + dirs[curr_dir_idx][0] # Propose new x based on current direction
- y_next = y + dirs[curr_dir_idx][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<width and 0<=y_next<height and not grid[y_next][x_next]):
- curr_dir_idx = (curr_dir_idx + 1)%4 # Turn 90 degrees clockwise
- x_next = x + dirs[curr_dir_idx][0] # New x based on corrected direction
- y_next = y + dirs[curr_dir_idx][1] # New y based on corrected direction
- #
- # Join grid into a single string and print it
- print("\n".join([" ".join(grid[row]) for row in range(height)]))
- #
- # Output:
- # 25 24 23 22 21
- # 10 09 08 07 20
- # 11 02 01 06 19
- # 12 03 04 05 18
- # 13 14 15 16 17
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement