diff options
Diffstat (limited to '2018/src/day08.cpp')
| -rw-r--r-- | 2018/src/day08.cpp | 88 |
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 | |||
| 6 | using namespace std; | ||
| 7 | |||
| 8 | namespace { | ||
| 9 | |||
| 10 | vector<int> | ||
| 11 | read_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 | |||
| 23 | void | ||
| 24 | part1(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 | |||
| 47 | void | ||
| 48 | part2(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 | |||
| 82 | int | ||
| 83 | main() | ||
| 84 | { | ||
| 85 | auto data = read_file("data/day08.txt"); | ||
| 86 | part1(data); | ||
| 87 | part2(data); | ||
| 88 | } | ||
