-
Notifications
You must be signed in to change notification settings - Fork 0
/
a.ts
93 lines (79 loc) · 2.09 KB
/
a.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
import { assertEquals } from "https://deno.land/std@0.167.0/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;
};
calcFileSize(fs);
const sumOfSub100k = dirSizes
.filter((x) => x <= 100_000)
.reduce((a, b) => a + b);
return sumOfSub100k;
}
Deno.test("example", () => {
const input = Deno.readTextFileSync("./07/example.txt");
const actual = solution(input);
const expected = 95437;
assertEquals(actual, expected);
});
Deno.test("puzzle input", { ignore: false }, () => {
const input = Deno.readTextFileSync("./07/input.txt");
const actual = solution(input);
const expected = 1723892;
assertEquals(actual, expected);
});