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
|
#include <fstream>
#include <iostream>
#include <iterator>
#include <map>
#include <numeric>
#include <vector>
using namespace std;
vector<long>
read_file(string_view filename)
{
fstream input{ filename };
return { istream_iterator<long>{ input }, {} };
}
void
part1(vector<long> data)
{
for ( size_t i = 0; i != 25; ++i ) {
vector<long> temp;
for ( const auto value: data ) {
if ( value == 0 ) {
temp.push_back(1);
continue;
}
auto str = to_string(value);
if ( str.size() % 2 == 0 ) {
auto len = str.size() / 2;
temp.push_back(stol(str.substr(0, len)));
temp.push_back(stol(str.substr(len)));
continue;
}
temp.push_back(value * 2024);
}
data.swap(temp);
}
cout << data.size() << endl;
}
void
part2(const vector<long>& data)
{
static const int MAX_DEPTH = 75;
map<tuple<long, int>, long> cache;
function<long(long, int)> count = [&](long value, int depth) -> long {
if ( cache.contains({ value, depth }) ) {
return cache[{ value, depth }];
}
if ( depth == MAX_DEPTH ) {
return 1;
}
if ( value == 0 ) {
return cache[{ value, depth }] = count(1, depth + 1);
}
auto str = to_string(value);
if ( str.size() % 2 == 0 ) {
auto len = str.size() / 2;
auto lhs = stol(str.substr(0, len));
auto rhs = stol(str.substr(len));
return cache[{ value, depth }] = count(lhs, depth + 1) + count(rhs, depth + 1);
}
return cache[{ value, depth }] = count(value * 2024, depth + 1);
};
cout << accumulate(data.begin(), data.end(), 0L, [&](long init, long value) { return init + count(value, 0); }) << endl;
}
int
main()
{
auto data = read_file("data/day11.txt");
part1(data);
part2(data);
}
|