题目地址:https://www.codewars.com/kata/521c2db8ddc89b9b7a0000c1/javascript
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]
思路:外圈遍历到内圈,顺时针遍历
javascript版本
1.自己
snail = function(array) {
// enjoy
let result = [];
while(array.length){
// 右方向
result = result.concat(array.shift());
// 下方向
for(let i = 0 ; i < array.length ; i++){
result.push(array[i].pop());
}
// 左方向
result = result.concat((array.pop()||[]).reverse());
// 上方向
for(let j = array.length-1 ; j >= 0 ; j--){
result.push(array[j].shift());
}
}
return result;
}
2.他人
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;
}
3.他人(目前还没看懂)
snail = function(array) {
var size = array.length;
if (size == 0)
return [];
if (size == 1)
return array[0];
var top = array[0].slice(0, -1);
var right = array.slice(0, -1).map(a => a[size - 1]);
var bottom = array[size -1].slice(1).reverse();
var left = array.slice(1).map(a => a[0]).reverse();
var inner = array.slice(1, -1).map(a => a.slice(1, -1));
return [].concat(top, right, bottom, left, snail(inner));
}
4.他人(目前还没看懂)
snail = function(array) {
var res = [];
while(array.length) {
res = res.concat(array.shift())
array = expand(array);
}
return res;
}
function expand(matrix){
return matrix.reduce(function(res, arr, i){
arr.forEach(function(n, j){
if (!res[j]) res[j] = [];
res[j][i] = n;
})
return res;
}, []).reverse();
}