Last active
January 3, 2016 06:49
-
-
Save grizwako/8425134 to your computer and use it in GitHub Desktop.
Cyclic table in python (for fun)
(spiral matrix)
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
""" | |
x*y table, number 1 is in lower left corner. | |
Go in clockwise direction and increase number by one for each cell. | |
""" | |
import itertools | |
x,y = 5,5 | |
table = [[0]*y for dummy in xrange(x)] | |
order = [ | |
lambda row, column:(row, column-1), #left | |
lambda row, column:(row-1, column), #up | |
lambda row, column:(row, column+1), #right | |
lambda row, column:(row+1, column) #down | |
] | |
order = itertools.cycle(order) #1,2,3,1,2,3,1,... | |
next_cell = order.next() #first we move left | |
row, column = x-1,y-1 | |
for i in range(1,x*y+1): | |
table[row][column] = i | |
_row,_column = next_cell(row,column) | |
# if new column would be (index out of bounds) | |
# or number is already set | |
if _column > y-1 or table[_row][_column]: | |
next_cell = order.next() | |
row,column = next_cell(row,column) | |
else: | |
row,column = _row,_column | |
print table |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment