-
Notifications
You must be signed in to change notification settings - Fork 0
/
07-SnakeSort2D.js
44 lines (37 loc) · 1.07 KB
/
07-SnakeSort2D.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
44
const N = parseInt(readline());
const arr = []
for (let i = 0; i < N; i++) {
const inputs = readline().split(' ');
const name = inputs[0];
const r = parseInt(inputs[1]);
const c = parseInt(inputs[2]);
arr.push({ name: name, rows: r, cols: c })
}
function lazySnakeEatingOrder(array) {
let result = []
// ascending order by rows
array.sort((a, b) => a.rows - b.rows)
let rows = {}
array.forEach((item) => {
if (!rows[item.rows]) {
rows[item.rows] = [];
}
rows[item.rows].push(item);
});
Object.values(rows).forEach((rowArray, index) => {
if (index % 2 === 0) {
// ascending order by cols
rowArray.sort((a, b) => a.cols - b.cols);
} else {
// descending order by cols
rowArray.sort((a, b) => b.cols - a.cols);
}
});
Object.values(rows).forEach((rowArray) => {
rowArray.forEach(item => {
result.push(item.name)
})
})
return result.join(",")
}
console.log(lazySnakeEatingOrder(arr));