-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathsnail.js
More file actions
51 lines (50 loc) · 1.2 KB
/
Copy pathsnail.js
File metadata and controls
51 lines (50 loc) · 1.2 KB
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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
/**
* 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 en empty array inside an array [[]].
*
* Kata URL: https://www.codewars.com/kata/521c2db8ddc89b9b7a0000c1
*
*/
snail = function (array) {
let result = [];
while (array.length > 0) {
result = result.concat(array.shift());
for (let i = 0; i < array.length; i++) {
result.push(array[i].pop());
}
if (array.length > 0) {
result = result.concat(array.pop().reverse());
}
for (let i = array.length - 1; i >= 0; i--) {
result.push(array[i].shift());
}
}
return result;
};