【CodeWars】Snail Sort
地址:https://www.codewars.com/kata/521c2db8ddc89b9b7a0000c1/train/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]
This image will illustrate things more clearly:
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 [[]].
我的答案:
// 规律:(0,0)(0,1)j变化,递增
// (0,2)(1,2)i变化,递增
// (2,2)(2,1)j变化,递减
const snail = (array) => {
const res = [];
let len = array.length;
if (len === 1) {
return array[0];
}
let times = 0;
let i = 0;
let j = 0;
let k = 0;
for (times = len; times > 0; times = times - 2) {
// 最外层循环,走完一次就是外层的一圈
// i,j初始值由(0,0)变成(1,1),打印一圈,ij的初始位置就往里挪动一位
for (k = 1; k < times; k++, j++) {
res.push(array[i][j]);
}
for (k = 1; k < times; k++, i++) {
res.push(array[i][j]);
}
for (k = 1; k < times; k++, j--) {
res.push(array[i][j]);
}
for (k = 1; k < times; k++, i--) {
res.push(array[i][j]);
}
// 为了让下一个循环的ij位置从(1,1)开始,分别加1
i = i + 1;
j = j + 1;
}
if (len % 2 === 1) {
i = i - 1;
j = j - 1;
res.push(array[i][j]);
}
return res;
};
console.log(
snail([
[1, 2, 3],
[4, 5, 6],
[7, 8, 9],
])
);
打印结果:[
1, 2, 3, 6, 9,
8, 7, 4, 5
]