見習村21 - Snail

21 - Snail

Don’t say so much, just coding…

Instruction

Snail Sort

Given an n x n array, return the array elements arranged from outermost elements to the middle element, traveling clockwise.

1
2
3
4
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:

1
2
3
4
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 en empty array inside an array [[]].

Ruby

Init

1
2
3
def snail(array)
# enjoy
end

Sample Testing

1
2
3
4
5
6
def test input , expected
output = snail(input)
Test.expect(expected == output, "When snail(#{input}) expected #{expected} but got #{output}")
end

test( [[1,2,3],[4,5,6],[7,8,9]] , [1, 2, 3, 6, 9, 8, 7, 4, 5])

Javascript

Init

1
2
3
snail = function(array) {
// enjoy
}

Sample Testing

1
2
3
4
5
Test.assertDeepEquals(snail([[]]), []);
Test.assertDeepEquals(snail([[1]]), [1]);
Test.assertDeepEquals(snail([[1, 2, 3], [4, 5, 6], [7, 8, 9]]), [1, 2, 3, 6, 9, 8, 7, 4, 5]);
Test.assertDeepEquals(snail([[1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20], [21, 22, 23, 24, 25]]), [1, 2, 3, 4, 5, 10, 15, 20, 25, 24, 23, 22, 21, 16, 11, 6, 7, 8, 9, 14, 19, 18, 17, 12, 13]);
Test.assertDeepEquals(snail([[1, 2, 3, 4, 5, 6], [20, 21, 22, 23, 24, 7], [19, 32, 33, 34, 25, 8], [18, 31, 36, 35, 26, 9], [17, 30, 29, 28, 27, 10], [16, 15, 14, 13, 12, 11]]), [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, 33, 34, 35, 36]);

Thinking

想法(1): 需要花時間找一下規律,每次將陣列取第一個的時候,後面剩餘的陣列必須還有些動作來轉換
想法(2): 轉換直至陣列為空為止,可以透過遞迴或者是 while 迴圈來寫

https://ithelp.ithome.com.tw/upload/images/20201006/20120826BoD8viU9wc.jpg
圖片來源:Unsplash Dagny Reese

Hint & Reference

Solution

Ruby

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# Solution 1
def snail(array)
result = []
while array.flatten.any?
result << array.shift
array = array.transpose.reverse
end
result.flatten
end

# Solution 2
def snail(array)
array.empty? ? [] : array.shift + snail(array.transpose.reverse)
end

Javascript

1
2
3
4
5
6
7
8
9
10
// Solution 1
function snail(array) {
var vector = [];
while (array.length) {
vector.push(...array.shift());
array.map(row => vector.push(row.pop()));
array.reverse().map(row => row.reverse());
}
return vector;
}