aboutsummaryrefslogtreecommitdiff
path: root/2024/src
diff options
context:
space:
mode:
Diffstat (limited to '2024/src')
-rw-r--r--2024/src/day22.cpp42
1 files changed, 42 insertions, 0 deletions
diff --git a/2024/src/day22.cpp b/2024/src/day22.cpp
index b103986..7fdc40e 100644
--- a/2024/src/day22.cpp
+++ b/2024/src/day22.cpp
@@ -1,6 +1,8 @@
1#include <cstdlib> 1#include <cstdlib>
2#include <fstream> 2#include <fstream>
3#include <iostream> 3#include <iostream>
4#include <map>
5#include <set>
4#include <vector> 6#include <vector>
5using namespace std; 7using namespace std;
6 8
@@ -20,6 +22,7 @@ read_file(string_view filename)
20unsigned long 22unsigned long
21step(unsigned long value) 23step(unsigned long value)
22{ 24{
25 // compiler will optimize these calculations
23 value = (value ^ (value * 64)) % 16777216; 26 value = (value ^ (value * 64)) % 16777216;
24 value = (value ^ (value / 32)) % 16777216; 27 value = (value ^ (value / 32)) % 16777216;
25 value = (value ^ (value * 2048)) % 16777216; 28 value = (value ^ (value * 2048)) % 16777216;
@@ -39,9 +42,48 @@ part1(const vector<unsigned long>& values)
39 cout << sum << endl; 42 cout << sum << endl;
40} 43}
41 44
45void
46part2(const vector<unsigned long>& values)
47{
48 using seq_type = tuple<unsigned long, unsigned long, unsigned long, unsigned long>;
49
50 map<seq_type, unsigned long> total;
51
52 for ( auto value: values ) {
53 vector<unsigned long> list{ value % 10 };
54
55 for ( int i = 0; i != 2000; ++i ) {
56 value = step(value);
57 list.emplace_back(value % 10);
58 }
59
60 set<seq_type> seen;
61
62 for ( size_t idx = 4; idx < list.size(); ++idx ) {
63 const auto a = list[idx - 4];
64 const auto b = list[idx - 3];
65 const auto c = list[idx - 2];
66 const auto d = list[idx - 1];
67 const auto e = list[idx];
68
69 seq_type seq{ b - a, c - b, d - c, e - d };
70
71 if ( seen.contains(seq) ) {
72 continue;
73 }
74 seen.insert(seq);
75
76 total[seq] += e;
77 }
78 }
79
80 cout << ranges::max_element(total, [](const auto& lhs, const auto& rhs) { return lhs.second < rhs.second; })->second << endl;
81}
82
42int 83int
43main() 84main()
44{ 85{
45 auto data = read_file("data/day22.txt"); 86 auto data = read_file("data/day22.txt");
46 part1(data); 87 part1(data);
88 part2(data);
47} 89}