Skip to content

Instantly share code, notes, and snippets.

@mahmoud
Created March 23, 2015 00:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mahmoud/86c8bc2860e65853b855 to your computer and use it in GitHub Desktop.
Save mahmoud/86c8bc2860e65853b855 to your computer and use it in GitHub Desktop.
def main():
assert gen_matrix(4, 3) == [[1, 2, 3, 4], [5, 6, 7, 8], [9, 10, 11, 12]]
print_matrix(gen_matrix(4, 6))
# 1, 2, 3, 4, 8, 12, 11, 10, 9, 5, 6, 7
def gen_matrix(width, height):
ret = [range(1 + width * ih, 1 + width * (ih + 1)) for ih in range(height)]
return ret
DIRECTIONS = range(4)
GO_RIGHT, GO_DOWN, GO_LEFT, GO_UP = DIRECTIONS
def print_matrix(sequences):
if not sequences:
return # nothing to print
width = len(sequences[0])
height = len(sequences)
min_iw, min_ih = 0, 0
max_iw, max_ih = width - 1, height - 1
S, di, i, total = sequences, 0, 0, (width * height)
while i < total:
cur_dir = di % len(DIRECTIONS)
if cur_dir == GO_RIGHT:
for iw in range(min_iw, max_iw + 1):
i += 1
print S[min_ih][iw]
min_ih += 1
elif cur_dir == GO_DOWN:
for ih in range(min_ih, max_ih + 1):
i += 1
print S[ih][max_iw]
max_iw -= 1
elif cur_dir == GO_LEFT:
for iw in range(max_iw, min_iw - 1, -1):
i += 1
print S[max_ih][iw]
max_ih -= 1
elif cur_dir == GO_UP:
for ih in range(max_ih, min_ih - 1, -1):
i += 1
print S[ih][min_iw]
min_iw += 1
di += 1
return
# TODO: is there a analytical way to know the ending coordinates
if __name__ == '__main__':
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment