aboutsummaryrefslogtreecommitdiff
path: root/2024/src
diff options
context:
space:
mode:
Diffstat (limited to '2024/src')
-rw-r--r--2024/src/day07.cpp59
1 files changed, 59 insertions, 0 deletions
diff --git a/2024/src/day07.cpp b/2024/src/day07.cpp
index 9b16b76..663e077 100644
--- a/2024/src/day07.cpp
+++ b/2024/src/day07.cpp
@@ -53,10 +53,69 @@ part1(const vector<tuple<long, vector<long>>>& data)
53 cout << sum << endl; 53 cout << sum << endl;
54} 54}
55 55
56size_t
57ipow(size_t base, size_t exp) // NOLINT
58{
59 size_t result = 1;
60 while ( exp != 0 ) {
61 if ( (exp & 1U) == 1 ) {
62 result *= base;
63 }
64 exp >>= 1U;
65 base *= base;
66 }
67
68 return result;
69}
70
71bool
72can_evaluated2(long first, const vector<long>& values)
73{
74 const auto N = ipow(3, values.size() - 1); // NOLINT
75
76 for ( unsigned long pattern = 0; pattern != N; ++pattern ) {
77 auto test_pattern = pattern;
78
79 long result = values.at(0);
80 for ( size_t idx = 1; idx < values.size(); ++idx ) {
81 auto rem = test_pattern % 3;
82
83 if ( rem == 0 ) {
84 result += values.at(idx);
85 }
86 else if ( rem == 1 ) {
87 result *= values.at(idx);
88 }
89 else {
90 result = stol(to_string(result) + to_string(values.at(idx)));
91 }
92
93 test_pattern /= 3;
94 }
95 if ( first == result ) {
96 return true;
97 }
98 }
99 return false;
100}
101
102void
103part2(const vector<tuple<long, vector<long>>>& data)
104{
105 long sum = 0;
106 for ( const auto& [first, values]: data ) {
107 if ( can_evaluated2(first, values) ) {
108 sum += first;
109 }
110 }
111 cout << sum << endl;
112}
113
56int 114int
57main() 115main()
58{ 116{
59 auto data = read_file("data/day07.txt"); 117 auto data = read_file("data/day07.txt");
60 118
61 part1(data); 119 part1(data);
120 part2(data);
62} 121}