-
Notifications
You must be signed in to change notification settings - Fork 0
/
aoc22day7.cpp
134 lines (106 loc) · 3.02 KB
/
aoc22day7.cpp
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
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
// Day 7: No Space Left On Device
#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
using namespace std;
struct File {
string name;
int size;
File(string name_, int size_) {
name = name_;
size = size_;
}
};
struct Directory {
Directory *parent;
string name;
vector<Directory *> dirs = {};
vector<File> files = {};
Directory(Directory *parent_, string name_) {
parent = parent_;
name = name_;
}
int get_size() {
int size = 0;
for (Directory *dir : dirs) {
size += dir->get_size();
}
for (File &file : files) {
size += file.size;
}
return size;
}
int get_small_dirs_size() {
int size = 0;
for (Directory *dir : dirs) {
size += dir->get_small_dirs_size();
int dir_size = dir->get_size();
if (dir_size <= 100000) {
size += dir_size;
}
}
return size;
}
int get_smallest_sufficient_dir_size(int minimum) {
int size = get_size();
if (size < minimum) {
size = -1;
}
for (Directory *dir : dirs) {
int dir_size = dir->get_smallest_sufficient_dir_size(minimum);
if ((dir_size < size || size == -1) && dir_size != -1) {
size = dir_size;
}
}
return size;
}
};
void delete_dir(Directory *dir) {
for (Directory *child_dir : dir->dirs) {
delete_dir(child_dir);
}
delete dir;
}
int main() {
ifstream file("aoc22day7_data.txt");
Directory *root = new Directory(NULL, "/");
Directory *current_dir = root;
for (string line; getline(file, line);) {
vector<string> tokens;
istringstream stream(line);
for (string word; stream >> word; tokens.push_back(word)) {}
if (tokens[0] == "$" && tokens[1] == "cd") {
if (tokens[2] == "..") {
current_dir = current_dir->parent;
} else {
for (Directory *dir : current_dir->dirs) {
if (dir->name == tokens[2]) {
current_dir = dir;
break;
}
}
}
} else if (tokens[0] == "dir") {
current_dir->dirs.push_back(new Directory(current_dir, tokens[1]));
} else {
try {
current_dir->files.push_back(
File(tokens[1], stoi(tokens[0]))
);
} catch (invalid_argument) {
continue;
}
}
}
cout << "[PART 1] Total size of small directories: "
<< root->get_small_dirs_size()
<< "\n";
cout << "[PART 2] Size of smallest sufficient directory: "
<< root->get_smallest_sufficient_dir_size(
30000000 - (70000000 - root->get_size())
)
<< "\n";
delete_dir(root);
}