-
Notifications
You must be signed in to change notification settings - Fork 0
/
7.js
102 lines (88 loc) · 1.99 KB
/
7.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
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
// Total duration: 21 min (rounded to the nearest minute)
// Started at: 19:09
// First star at: 19:26
// Second star at: 19:30
const solveProblem = (data) => {
// Parse data
const lines = data.split("\n").slice(0, -1);
const fileSystem = {};
let currentStack = [fileSystem];
lines.forEach(line => {
if (line == "$ cd /") {
currentDirectory = [];
return;
}
if (line == "$ cd ..") {
currentStack = currentStack.slice(0, -1);
return
}
if (line.startsWith("$ cd ")) {
const name = line.slice(5);
directory = currentStack.at(-1)[name];
currentStack.push(directory);
return;
}
if (line.startsWith("$ ls")) {
return;
}
if (line.startsWith("dir ")) {
const name = line.slice(4);
currentStack.at(-1)[name] = {}
return;
}
if (true) {
const [sizeStr, name] = line.split(" ");
const size = Number(sizeStr);
currentStack.at(-1)[name] = size;
}
})
// Part 1
const directories = [];
const traverseDir = (name, dir) => {
let size = 0;
Object.keys(dir).forEach(name => {
const file = dir[name];
if (typeof file == "number") {
size += file;
return;
}
size += traverseDir(name, file);
});
directories.push({name, size})
return size
}
traverseDir("/", fileSystem);
let sum = 0;
directories.forEach(dir => {
if (dir.size <= 100_000) {
sum += dir.size;
}
})
console.log(sum);
console.log("");
// Part 2
const totalSize = directories.find(d => d.name == "/").size;
const spaceToRemove = totalSize - 40_000_000;
let bestSize = Infinity;
directories.forEach(dir => {
if (dir.size >= spaceToRemove && dir.size < bestSize) {
bestSize = dir.size;
}
})
console.log(bestSize);
console.log("");
};
// Library code
const fs = require("fs");
const path = require('path');
const day = path.parse(__filename).name;
const files = [
`${day}-test`,
`${day}`,
];
files.forEach(file => {
fs.readFile(`./${file}.txt`, "utf8", (_, data) => {
console.log(`Data from file ${file}.txt`);
solveProblem(data);
});
});