Snail

题目

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 [[]].

分析

看注释

答案

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
let snail = function (array) {
// 定义返回值
let snail = [];
while (array.length > 0) {
// shift返回数组的第一个元素塞到结果里
// concat弹出数组的第一个元素
snail = snail.concat(array.shift());
// 遍历处理后的数组,pop弹出数组的最后一个元素
for (let i in array) {
snail.push(array[i].pop());
}
//遍历处理后的数组,把数组顺序翻转
for (let i in array) {
array[i].reverse();
}
// 最后再次翻转数组
array.reverse();
}
return snail;
}