Skip to content

Instantly share code, notes, and snippets.

@meyer1994
Created September 8, 2018 19:54
Show Gist options
  • Save meyer1994/f96cf4cdafa0fe633e53bef5c7d53eb0 to your computer and use it in GitHub Desktop.
Save meyer1994/f96cf4cdafa0fe633e53bef5c7d53eb0 to your computer and use it in GitHub Desktop.
Iterate over an sqaure matrix, from the inside out
'''
Created this for a school project. It works for both, matrices with even or odd orders.
'''
def iterate(mat):
order = len(mat)
cycles = order // 2
# odd
if order % 2 == 1:
yield mat[cycles][cycles]
calc_n = lambda i: i * 2 + 2
calc_c = lambda i : cycles + 1 + i
else:
calc_c = lambda i : cycles + i
calc_n = lambda i: i * 2 + 1
for i in range(cycles):
x = calc_c(i)
y = calc_c(i)
n = calc_n(i)
# left
for _ in range(n):
yield mat[y][x]
x -= 1
# down
for _ in range(n):
yield mat[y][x]
y -= 1
# right
for _ in range(n):
yield mat[y][x]
x += 1
# up
for _ in range(n):
yield mat[y][x]
y += 1
from pprint import pprint
# Create a simple matrix, for test
q = 4
m = [ [ str(j * q + i).rjust(2) for i in range(q) ] for j in range(q) ]
pprint(m[::-1])
# Out:
# [['12', '13', '14', '15'],
# [' 8', ' 9', '10', '11'],
# [' 4', ' 5', ' 6', ' 7'],
# [' 0', ' 1', ' 2', ' 3']]
print(list(iterate(m)))
# Out:
# ['10', ' 9', ' 5', ' 6', '15', '14', '13', '12', ' 8', ' 4', ' 0', ' 1', ' 2', ' 3', ' 7', '11']
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment