-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.cpp
122 lines (101 loc) · 3.09 KB
/
main.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
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <regex>
#include <map>
std::vector<std::string> read_lines(std::string filename) {
std::vector<std::string> lines;
std::ifstream file(filename);
std::string line;
while (std::getline(file, line)) {
lines.push_back(line);
}
return lines;
}
std::string join_path(std::vector<std::string> cwd) {
std::string result;
for (const auto& path : cwd) {
result += path + "/";
}
return result.substr(1);
}
auto process_lines(const std::vector<std::string>&& lines) {
const std::regex file_regex(R"--(^(\d+) (.+)$)--");
std::vector<std::string> cwd;
std::map<std::string, uint64_t> files;
std::string current_ls_path;
for (const auto line : lines) {
if (line.size() >= 1 && line[0] == '$') {
if (line.substr(0, 4) == "$ cd") {
current_ls_path = "";
const auto path = line.substr(5);
if (path == "..") {
cwd.pop_back();
} else {
cwd.push_back(path);
}
} else if (line.substr(0, 4) == "$ ls") {
current_ls_path = join_path(cwd);
}
} else {
if (current_ls_path.size() > 0) {
std::smatch match;
if (std::regex_match(line, match, file_regex)) {
const auto size = std::stoi(match[1]);
const auto name = match[2].str();
files.emplace(current_ls_path + name, size);
}
}
}
}
return files;
}
auto get_parent_dir(const std::string& path) {
auto pos = path.find_last_of('/');
if (pos != std::string::npos) {
return path.substr(0, pos);
}
return std::string("");
}
auto group_into_dirs(const std::map<std::string, uint64_t>&& files) {
std::map<std::string, uint64_t> dirs;
for (const auto& file : files) {
const auto& path = file.first;
const auto& size = file.second;
auto pp = get_parent_dir(path);
dirs[pp] = dirs[pp] + size;
while (pp != "") {
pp = get_parent_dir(pp);
dirs[pp] = dirs[pp] + size;
}
}
return dirs;
}
int main(int argc, char** argv) {
auto lines = read_lines(argv[1]);
auto files = process_lines(std::move(lines));
auto dirs = group_into_dirs(std::move(files));
std::cout << "part1: ";
uint64_t sum = 0;
for (const auto& dir : dirs) {
if (dir.second > 100000u) {
continue;
}
sum += dir.second;
}
std::cout << sum << std::endl;
std::cout << "part2: ";
const auto total = 70000000;
const auto update = 30000000;
const auto free = total - dirs[""];
const auto needed = update - free;
std::vector<uint64_t> candidates;
for (const auto& dir : dirs) {
if (dir.second >= needed) {
candidates.push_back(dir.second);
}
}
std::cout << *std::min_element(candidates.begin(), candidates.end()) << std::endl;
return 0;
}