-
Notifications
You must be signed in to change notification settings - Fork 25
/
(4 kyu) Snail.js
43 lines (41 loc) · 1008 Bytes
/
(4 kyu) Snail.js
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
snail = function(array) {
const [N, result] = [array[0].length, []];
let [L, row, col, direction] = [N * N, 0, 0, 'RIGHT'];
let [borderRight, borderLeft, borderTop, borderBottom] = [N - 1, 0, 0, N - 1];
while (L--) {
result.push(array[row][col]);
switch (direction) {
case 'RIGHT':
col >= borderRight && ((direction = 'DOWN'), borderTop++);
break;
case 'LEFT':
col <= borderLeft && ((direction = 'UP'), borderBottom--);
break;
case 'DOWN':
row >= borderBottom && ((direction = 'LEFT'), borderRight--);
break;
case 'UP':
row <= borderTop && ((direction = 'RIGHT'), borderLeft++);
break;
default:
break;
}
switch (direction) {
case 'RIGHT':
col++;
break;
case 'LEFT':
col--;
break;
case 'UP':
row--;
break;
case 'DOWN':
row++;
break;
default:
break;
}
}
return result;
};