-
Notifications
You must be signed in to change notification settings - Fork 0
/
7.ts
90 lines (82 loc) · 2.2 KB
/
7.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
import './utils/helpers.ts';
let data = await Deno.readTextFile('7.txt');
// let data = `$ 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`;
interface File { name: string; size: number; isDirectory: boolean; }
let pwd: string[] = [];
const files: Record<string, File[]> = {};
for (const line of data.lines()) {
const words = line.trim().split(' ');
if (words[0] === '$') {
const [,command, arg1] = words;
if (command === 'cd') {
if (arg1 === '/') pwd = [];
else if (arg1 === '..') pwd.pop();
else pwd.push(arg1);
}
}
else {
const [p1, p2] = words;
const path = pwd.join('/');
const filesInPath:File[] = files[path] || [];
const isDirectory = p1 === 'dir';
filesInPath.push({
name: p2,
size: isDirectory ? 0 : parseInt(p1),
isDirectory,
});
files[path] = filesInPath;
}
}
function getFilesForDir(dir: string): File[] {
return Object.keys(files).filter(key => key === dir).map(key => files[key])[0];
}
function sizeOfDir(parent: File[], parentDirs: string): number {
if (!parent?.length) return 0;
const filesSize = parent.map(p => p.size).sum();
const dirSizes = parent.filter(p => p.isDirectory).map(p => {
let newParent = parentDirs + '/' + p.name;
if (newParent.startsWith('/')) newParent = newParent.substring(1);
const files = getFilesForDir(newParent);
return sizeOfDir(files, newParent);
});
return filesSize + dirSizes.sum();
}
// part 1
const sum = Object.keys(files)
.map(file => sizeOfDir(files[file], file))
.filter(size => size <= 100000)
.sum();
console.log(sum);
// part 2
const systemSize = 70000000;
const freeNeeded = 30000000;
const used = sizeOfDir(files[''], '');
const unused = systemSize - used;
const result = Object.keys(files)
.map(key => sizeOfDir(files[key], key))
.filter(size => unused + size >= freeNeeded)
.sortDesc()
.last();
console.log(result);