Skip to content

Instantly share code, notes, and snippets.

@observerss
Forked from nevill/calculation.rb
Last active December 21, 2015 12:19
Show Gist options
  • Save observerss/6304947 to your computer and use it in GitHub Desktop.
Save observerss/6304947 to your computer and use it in GitHub Desktop.
def chop(matrix, box, direction, results=None):
if results is None:
results = []
x1, y1, x2, y2 = box
w = x2 - x1 + 1
h = y2 - y1 + 1
if w <= 0 or h <= 0:
return results
else:
if direction == 0:
results.extend( [matrix[y1][x] for x in range(x1, x2+1)] )
y1 += 1
elif direction == 1:
results.extend( [matrix[y][x2] for y in range(y1, y2+1)] )
x2 -= 1
elif direction == 2:
results.extend( [matrix[y2][x] for x in range(x2, x1-1, -1)] )
y2 -= 1
elif direction == 3:
results.extend( [matrix[y][x1] for y in range(y2, y1-1, -1)] )
x1 += 1
return chop(matrix, (x1, y1, x2, y2), (direction+1)%4, results=results)
def traverse(matrix):
box = (0, 0, len(matrix[0])-1, len(matrix)-1)
return chop(matrix, box, 0)\
# tests
assert traverse([[12, 32], [7, 34]]) \
== [12, 32, 34, 7]
assert traverse([ [12, 17, 9], [19, 28, 11], [43, 7, 34] ]) \
== [12, 17, 9, 11, 34, 7, 43, 19, 28]
assert traverse([ [12, 32, 9, 11], [8, 54, 76, 23], [27, 18, 25, 9], [11, 23, 78, 63] ]) \
== [12, 32, 9, 11, 23, 9, 63, 78, 23, 11, 27, 8, 54, 76, 25, 18]
assert traverse([ [12, 32, 9, 11, 34], [8, 54, 76, 23, 7], [27, 18, 25, 9, 43], [11, 23, 78, 63, 19], [9, 22, 56, 31, 5] ]) \
== [12, 32, 9, 11, 34, 7, 43, 19, 5, 31, 56, 22, 9, 11, 27, 8, 54, 76, 23, 9, 63, 78, 23, 18, 25]
assert traverse([ [12, 17], [9, 11], [19, 28] ]) \
== [12, 17, 11, 28, 19, 9]
assert traverse([[12, 17, 9, 7, 21, 10], [19, 28, 11, 25, 2, 6], [10, 3, 8, 13, 4, 29], [5, 12, 9, 14, 31, 18]]) \
== [12, 17, 9, 7, 21, 10, 6, 29, 18, 31, 14, 9, 12, 5, 10, 19, 28, 11, 25, 2, 4, 13, 8, 3]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment