Skip to content

Instantly share code, notes, and snippets.

@mvallebr
Last active November 16, 2016 10:58
Show Gist options
  • Select an option

  • Save mvallebr/7e5c4ac14d4a21abcd96bd64d706dc8d to your computer and use it in GitHub Desktop.

Select an option

Save mvallebr/7e5c4ac14d4a21abcd96bd64d706dc8d to your computer and use it in GitHub Desktop.
"""
Description:
Snail Sort
Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise.
array = [[1,2,3],
[4,5,6],
[7,8,9]]
snail(array) #=> [1,2,3,6,9,8,7,4,5]
For better understanding, please follow the numbers of the next array consecutively:
array = [[1,2,3],
[8,9,4],
[7,6,5]]
snail(array) #=> [1,2,3,4,5,6,7,8,9]
NOTE: The idea is not sort the elements from the lowest value to the highest; the idea is to traverse the 2-d array in a clockwise snailshell pattern.
NOTE 2: The 0x0 (empty matrix) is represented as [[]]
"""
def direction_vector(direction):
return {
0: (0, 1), # LEFT
1: (1, 0), # DOWN
2: (0, -1), # RIGHT
3: (-1, 0) # UP
}[direction]
def snail(array):
n = len(array[0])
result = []
x, y = 0, -1 # start point
direction = 0 # start direction
offset = 0
while n - offset > 0:
dx, dy = direction_vector(direction)
for _ in range(n - offset):
x, y = x + dx, y + dy
result.append(array[x][y])
direction = (direction + 1) % 4
if direction == 1 or direction == 3:
offset += 1
return result
# Tests
array = [[]]
expected = []
test.assert_equals(snail(array), expected)
array = [[1,2,3],
[4,5,6],
[7,8,9]]
expected = [1,2,3,6,9,8,7,4,5]
test.assert_equals(snail(array), expected)
array = [[1,2,3],
[8,9,4],
[7,6,5]]
expected = [1,2,3,4,5,6,7,8,9]
test.assert_equals(snail(array), expected)
array = [[1,2,3,4],
[5,6,7,8],
[9,10,11,12],
[13,14,15,16]]
expected = [1,2,3,4,8,12,16,15,14,13,9,5,6,7,11,10]
test.assert_equals(snail(array), expected)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment