aboutsummaryrefslogtreecommitdiff
path: root/2024
diff options
context:
space:
mode:
authorThomas Schmucker <ts@its1.de>2024-12-07 17:20:45 +0100
committerThomas Schmucker <ts@its1.de>2024-12-07 17:20:45 +0100
commitb6bd355be739f94206046b7247da9c387b786474 (patch)
treeb0be340bfbb3465dfd04bee04c01cb877d2a8992 /2024
parent50ffa7beba18811b74945b762a86da3fd5a795e5 (diff)
downloadadvent-of-code-b6bd355be739f94206046b7247da9c387b786474.tar.gz
advent-of-code-b6bd355be739f94206046b7247da9c387b786474.tar.bz2
advent-of-code-b6bd355be739f94206046b7247da9c387b786474.zip
aoc 2024, day 7, part 2
Diffstat (limited to '2024')
-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}