aboutsummaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--2024/src/day11.cpp38
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>
5using namespace std; 7using 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
42void
43part2(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
40int 77int
41main() 78main()
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}