Matrix

in #ita2 months ago

RIGHT = 0
DOWN = 1
LEFT = 2
UP = 3

def next_position(i, j, direction):
if direction == RIGHT:
return i, j+1
if direction == DOWN:
return i+1,j
if direction == LEFT:
return i, j-1
return i-1,j # for direction UP

def spiral_matrix(size):
matrix = [[0 for i in range(size)] for j in range(size)]
i = 0
j = 0
direction = RIGHT
for n in range(1,(size**2)+1):
matrix[i][j] = n
i_test, j_test = next_position(i,j,direction)
if i_test not in range(size) or j_test not in range(size) or matrix[i_test][j_test]!=0:
if direction == UP:
direction = RIGHT
else: # funziona con valori messi da noi perche´ messi nell´ordine giusto
direction +=1
i, j = next_position(i, j, direction)
return matrix