diff options
| author | Thomas Schmucker <ts@its1.de> | 2024-12-11 17:54:37 +0100 |
|---|---|---|
| committer | Thomas Schmucker <ts@its1.de> | 2024-12-11 17:54:37 +0100 |
| commit | 82478551ad59a6ff7ac095f16775077981b1e14a (patch) | |
| tree | e3586851720fab1e2ba26ad7634c83f090f7e99c /2024 | |
| parent | 585d3537ed50602ae706be1ed9b7bb59a4a98976 (diff) | |
| download | advent-of-code-82478551ad59a6ff7ac095f16775077981b1e14a.tar.gz advent-of-code-82478551ad59a6ff7ac095f16775077981b1e14a.tar.bz2 advent-of-code-82478551ad59a6ff7ac095f16775077981b1e14a.zip | |
aoc 2024, day 11, part 2
Diffstat (limited to '2024')
| -rw-r--r-- | 2024/src/day11.cpp | 38 |
1 files changed, 38 insertions, 0 deletions
diff --git a/2024/src/day11.cpp b/2024/src/day11.cpp index f31e30b..ee8f57b 100644 --- a/2024/src/day11.cpp +++ b/2024/src/day11.cpp | |||
| @@ -1,6 +1,8 @@ | |||
| 1 | #include <fstream> | 1 | #include <fstream> |
| 2 | #include <iostream> | 2 | #include <iostream> |
| 3 | #include <iterator> | 3 | #include <iterator> |
| 4 | #include <map> | ||
| 5 | #include <numeric> | ||
| 4 | #include <vector> | 6 | #include <vector> |
| 5 | using namespace std; | 7 | using namespace std; |
| 6 | 8 | ||
| @@ -37,9 +39,45 @@ part1(vector<long> data) | |||
| 37 | cout << data.size() << endl; | 39 | cout << data.size() << endl; |
| 38 | } | 40 | } |
| 39 | 41 | ||
| 42 | void | ||
| 43 | part2(const vector<long>& data) | ||
| 44 | { | ||
| 45 | static const int MAX_DEPTH = 75; | ||
| 46 | |||
| 47 | map<tuple<long, int>, long> cache; | ||
| 48 | |||
| 49 | function<long(long, int)> count = [&](long value, int depth) -> long { | ||
| 50 | if ( cache.contains({ value, depth }) ) { | ||
| 51 | return cache[{ value, depth }]; | ||
| 52 | } | ||
| 53 | |||
| 54 | if ( depth == MAX_DEPTH ) { | ||
| 55 | return 1; | ||
| 56 | } | ||
| 57 | |||
| 58 | if ( value == 0 ) { | ||
| 59 | return cache[{ value, depth }] = count(1, depth + 1); | ||
| 60 | } | ||
| 61 | |||
| 62 | auto str = to_string(value); | ||
| 63 | if ( str.size() % 2 == 0 ) { | ||
| 64 | auto len = str.size() / 2; | ||
| 65 | auto lhs = stol(str.substr(0, len)); | ||
| 66 | auto rhs = stol(str.substr(len)); | ||
| 67 | |||
| 68 | return cache[{ value, depth }] = count(lhs, depth + 1) + count(rhs, depth + 1); | ||
| 69 | } | ||
| 70 | |||
| 71 | return cache[{ value, depth }] = count(value * 2024, depth + 1); | ||
| 72 | }; | ||
| 73 | |||
| 74 | cout << accumulate(data.begin(), data.end(), 0L, [&](long init, long value) { return init + count(value, 0); }) << endl; | ||
| 75 | } | ||
| 76 | |||
| 40 | int | 77 | int |
| 41 | main() | 78 | main() |
| 42 | { | 79 | { |
| 43 | auto data = read_file("data/day11.txt"); | 80 | auto data = read_file("data/day11.txt"); |
| 44 | part1(data); | 81 | part1(data); |
| 82 | part2(data); | ||
| 45 | } | 83 | } |
