-
Notifications
You must be signed in to change notification settings - Fork 0
/
07.js
74 lines (68 loc) · 1.81 KB
/
07.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
/**
* @param {string} d
*/
export const part1 = async d => {
const data = d.split('\n');
const directorySizes = new Map();
const cwd = [];
while (data.length) {
const line = data.shift();
const cmd = line.match(/^\$ (cd|ls)(?: (.*))?$/);
const file = line.match(/^(dir|\d+) (.+)$/);
if (cmd) {
if (cmd[1] == 'ls') continue;
if (cmd[2] == '/') {
cwd.splice(0, cwd.length);
cwd.push('root');
} else if (cmd[2] == '..') {
cwd.pop();
} else {
cwd.push(cwd[cwd.length - 1] + '/' + cmd[2]);
}
} else if (file) {
if (file[1] == 'dir') continue;
const size = parseInt(file[1], 10);
cwd.forEach((dir) => {
directorySizes.set(dir, (directorySizes.get(dir) ?? 0) + size);
});
} else {
console.log(line);
}
}
return Array.from(directorySizes.values()).filter((v) => v <= 100000).reduce((c, v) => c + v, 0);
};
/**
* @param {string} d
*/
export const part2 = async d => {
const data = d.split('\n');
const directorySizes = new Map();
const cwd = [];
while (data.length) {
const line = data.shift();
const cmd = line.match(/^\$ (cd|ls)(?: (.*))?$/);
const file = line.match(/^(dir|\d+) (.+)$/);
if (cmd) {
if (cmd[1] == 'ls') continue;
if (cmd[2] == '/') {
cwd.splice(0, cwd.length);
cwd.push('root');
} else if (cmd[2] == '..') {
cwd.pop();
} else {
cwd.push(cwd[cwd.length - 1] + '/' + cmd[2]);
}
} else if (file) {
if (file[1] == 'dir') continue;
const size = parseInt(file[1], 10);
cwd.forEach((dir) => {
directorySizes.set(dir, (directorySizes.get(dir) ?? 0) + size);
});
} else {
console.log(line);
}
}
const freeSpace = 70000000 - directorySizes.get('root');
const files = Array.from(directorySizes.entries()).filter((v) => v[1] > 30000000 - freeSpace).sort((a, b) => b[1] - a[1]);
return (files.pop())[1];
};