aboutsummaryrefslogtreecommitdiff
path: root/2018/src/day08.cpp
diff options
context:
space:
mode:
authorThomas Schmucker <ts@its1.de>2025-11-16 13:23:34 +0100
committerThomas Schmucker <ts@its1.de>2025-11-16 13:23:34 +0100
commit8c96639ec1f6757570510fc27f1c5fabece35eaf (patch)
tree3a2b2146b6e8a353fa4c5edd105790320cce2b26 /2018/src/day08.cpp
parentbdd35a7bee7f23c912d0c453abc263805d8d8ccf (diff)
downloadadvent-of-code-8c96639ec1f6757570510fc27f1c5fabece35eaf.tar.gz
advent-of-code-8c96639ec1f6757570510fc27f1c5fabece35eaf.tar.bz2
advent-of-code-8c96639ec1f6757570510fc27f1c5fabece35eaf.zip
aoc 2018, days 1-11
Diffstat (limited to '2018/src/day08.cpp')
-rw-r--r--2018/src/day08.cpp88
1 files changed, 88 insertions, 0 deletions
diff --git a/2018/src/day08.cpp b/2018/src/day08.cpp
new file mode 100644
index 0000000..9c2a093
--- /dev/null
+++ b/2018/src/day08.cpp
@@ -0,0 +1,88 @@
1#include <filesystem>
2#include <fstream>
3#include <iostream>
4#include <vector>
5
6using namespace std;
7
8namespace {
9
10vector<int>
11read_file(const filesystem::path& filename)
12{
13 ifstream file{ filename };
14 vector<int> data;
15
16 for ( int number{}; file >> number; ) {
17 data.emplace_back(number);
18 }
19
20 return data;
21}
22
23void
24part1(const vector<int>& data)
25{
26 size_t idx = 0;
27 int sum = 0;
28
29 function<void()> func = [&] {
30 auto count_child = data.at(idx++);
31 auto count_meta = data.at(idx++);
32
33 while ( count_child-- > 0 ) {
34 func();
35 }
36
37 while ( count_meta-- > 0 ) {
38 sum += data.at(idx++);
39 }
40 };
41
42 func();
43
44 cout << "Part 1: " << sum << '\n';
45}
46
47void
48part2(const vector<int>& data)
49{
50 size_t idx = 0;
51
52 function<int()> func = [&] {
53 const auto count_child = data.at(idx++);
54 const auto count_meta = data.at(idx++);
55
56 vector<int> child_values;
57 for ( int i = 0; i != count_child; ++i ) {
58 child_values.emplace_back(func());
59 }
60
61 int value = 0;
62 for ( int i = 0; i != count_meta; ++i ) {
63 auto meta = data.at(idx++);
64 if ( count_child == 0 ) {
65 value += meta;
66 }
67 else {
68 meta--;
69 if ( meta >= 0 && meta < count_child ) {
70 value += child_values[static_cast<size_t>(meta)];
71 }
72 }
73 }
74 return value;
75 };
76
77 cout << "Part 2: " << func() << '\n';
78}
79
80} // namespace
81
82int
83main()
84{
85 auto data = read_file("data/day08.txt");
86 part1(data);
87 part2(data);
88}