-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday7.js
More file actions
94 lines (86 loc) · 1.83 KB
/
day7.js
File metadata and controls
94 lines (86 loc) · 1.83 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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
import fs from 'fs';
const input = fs.readFileSync('inputs/day7.txt', 'utf8');
const sampleInput = `
$ cd /
$ ls
dir a
14848514 b.txt
8504156 c.dat
dir d
$ cd a
$ ls
dir e
29116 f
2557 g
62596 h.lst
$ cd e
$ ls
584 i
$ cd ..
$ cd ..
$ cd d
$ ls
4060174 j
8033020 d.log
5626152 d.ext
7214296 k`;
// - / (dir)
// - a (dir)
// - e (dir)
// - i (file, size=584)
// - f (file, size=29116)
// - g (file, size=2557)
// - h.lst (file, size=62596)
// - b.txt (file, size=14848514)
// - c.dat (file, size=8504156)
// - d (dir)
// - j (file, size=4060174)
// - d.log (file, size=8033020)
// - d.ext (file, size=5626152)
// - k (file, size=7214296)
const solveProblem = (input) => {
const lines = input.split('\n');
const path = [];
const sizes = {};
for (const line of lines) {
if (line.startsWith('$ cd')) {
const directory = line.substring(5);
if (directory === '..') {
path.pop();
} else {
path.push(directory);
}
} else if (line.startsWith('$ ls')) {
continue;
} else if (line.startsWith('dir')) {
continue;
} else {
const [size] = line.split(' ');
let currentPath = '';
for (let i = 0; i < path.length; i++) {
currentPath += path[i];
if (sizes[currentPath]) {
sizes[currentPath] += parseInt(size);
} else {
sizes[currentPath] = parseInt(size);
}
currentPath += '/';
}
}
}
const maxUsed = 70000000 - 30000000;
const totalUsed = sizes['/'];
const needToFree = totalUsed - maxUsed;
let p1 = 0;
let p2 = 1000000000;
for (const [key, value] of Object.entries(sizes)) {
if (value <= 100000) {
p1 += value;
}
if (value >= needToFree) {
p2 = Math.min(p2, value);
}
}
return { p1, p2 };
};
console.log(solveProblem(input));