Created
          July 24, 2019 20:50 
        
      - 
      
 - 
        
Save tymofij/92b50e85ed5e513687d40c8000f5c212 to your computer and use it in GitHub Desktop.  
    Creates a spiral of numbers in a matrix NxN
  
        
  
    
      This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
      Learn more about bidirectional Unicode characters
    
  
  
    
  | # creates a spiral of numbers in a matrix NxN | |
| from copy import copy | |
| def vortex(n): | |
| i = 1 | |
| row = [0] * n | |
| matrix = [copy(row) for _ in range(n)] | |
| pos_row = 0 | |
| pos_col = 0 | |
| dir = 'right' # 'left', 'up', 'down' | |
| stop = False | |
| while not stop: | |
| matrix[pos_row][pos_col] = i | |
| i += 1 | |
| if dir == 'right': | |
| if has_next(matrix, pos_row, pos_col, dir): | |
| pos_col += 1 | |
| continue | |
| else: | |
| if has_next(matrix, pos_row, pos_col, 'down'): | |
| dir = 'down' | |
| pos_row += 1 | |
| continue | |
| else: | |
| stop = True | |
| if dir == 'down': | |
| if has_next(matrix, pos_row, pos_col, dir): | |
| pos_row += 1 | |
| continue | |
| else: | |
| if has_next(matrix, pos_row, pos_col, 'left'): | |
| dir = 'left' | |
| pos_col -= 1 | |
| continue | |
| else: | |
| stop = True | |
| if dir == 'left': | |
| if has_next(matrix, pos_row, pos_col, dir): | |
| pos_col -= 1 | |
| continue | |
| else: | |
| if has_next(matrix, pos_row, pos_col, 'up'): | |
| dir = 'up' | |
| pos_row -= 1 | |
| continue | |
| else: | |
| stop = True | |
| if dir == 'up': | |
| if has_next(matrix, pos_row, pos_col, dir): | |
| pos_row -= 1 | |
| continue | |
| else: | |
| if has_next(matrix, pos_row, pos_col, 'right'): | |
| dir = 'right' | |
| pos_col += 1 | |
| continue | |
| else: | |
| stop = True | |
| return matrix | |
| def has_next(matrix, pos_row, pos_col, dir): | |
| size = len(matrix) | |
| if dir == 'right': | |
| return pos_col+1 < size and matrix[pos_row][pos_col+1] == 0 | |
| if dir == 'left': | |
| return pos_col-1 >= 0 and matrix[pos_row][pos_col-1] == 0 | |
| if dir == 'down': | |
| return pos_row+1 < size and matrix[pos_row+1][pos_col] == 0 | |
| if dir == 'up': | |
| return pos_row-1 >= 0 and matrix[pos_row-1][pos_col] == 0 | |
| return None | |
| assert vortex(1) == [[1]] | |
| assert vortex(2) == [[1, 2], [4, 3]] | |
| assert vortex(3) == [[1, 2, 3], [8, 9, 4], [7, 6, 5]] | |
| assert vortex(4) == [[1, 2, 3, 4], [12, 13, 14, 5], [11, 16, 15, 6], [10, 9, 8, 7]] | |
| for row in vortex(9): | |
| print(",".join(str(i).rjust(3) for i in row)) | 
  
    Sign up for free
    to join this conversation on GitHub.
    Already have an account?
    Sign in to comment