-
Notifications
You must be signed in to change notification settings - Fork 0
/
b.ts
97 lines (82 loc) · 2.25 KB
/
b.ts
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
import { assertEquals } from "https://deno.land/[email protected]/testing/asserts.ts";
type Dir = {
[name: string]: number | Dir;
};
const getDirFromCd = (dir: Dir, cd: string[]) => {
return cd.reduce((acc: Dir, d) => {
const next = acc[d];
if (typeof next === "number") {
throw new Error(`wrong path: ${cd}`);
}
return next;
}, dir);
};
function solution(input: string) {
const lines = input.split("\n");
const fs = {};
const currentDirPath: string[] = [];
lines.forEach((line) => {
const params = line.split(" ");
switch (params[0]) {
case "$": {
switch (params[1]) {
case "cd": {
const dest = params[2];
if (dest === "..") {
currentDirPath.pop();
} else {
const dir = getDirFromCd(fs, currentDirPath);
dir[dest] = {};
currentDirPath.push(dest);
}
break;
}
default:
break;
}
break;
}
default: {
if (params[0] === "dir") {
const dir = getDirFromCd(fs, currentDirPath);
dir[params[1]] = {};
} else {
const dir = getDirFromCd(fs, currentDirPath);
dir[params[1]] = Number(params[0]);
}
}
}
});
const dirSizes: number[] = [];
const calcFileSize = (current: Dir | number) => {
if (typeof current === "number") {
return current;
}
let s = 0;
for (const name in current) {
s += calcFileSize(current[name]);
}
dirSizes.push(s);
return s;
};
const rootSize = calcFileSize(fs);
const totalSpace = 70_000_000;
const updateSize = 30_000_000;
const neededSpace = updateSize - (totalSpace - rootSize);
const smallestThatFixesSpace = Math.min(
...dirSizes.filter((s) => s >= neededSpace),
);
return smallestThatFixesSpace;
}
Deno.test("example", () => {
const input = Deno.readTextFileSync("./07/example.txt");
const actual = solution(input);
const expected = 24933642;
assertEquals(actual, expected);
});
Deno.test("puzzle input", { ignore: false }, () => {
const input = Deno.readTextFileSync("./07/input.txt");
const actual = solution(input);
const expected = 8474158;
assertEquals(actual, expected);
});