aboutsummaryrefslogtreecommitdiff
path: root/2024
diff options
context:
space:
mode:
authorThomas Schmucker <ts@its1.de>2024-12-07 08:22:16 +0100
committerThomas Schmucker <ts@its1.de>2024-12-07 08:22:16 +0100
commit50ffa7beba18811b74945b762a86da3fd5a795e5 (patch)
treee3f14cfea791dd8fbc33430f85ade12e3e91d13a /2024
parent9af62d7c591b7893f47f111784224eb0d5c5e4ff (diff)
downloadadvent-of-code-50ffa7beba18811b74945b762a86da3fd5a795e5.tar.gz
advent-of-code-50ffa7beba18811b74945b762a86da3fd5a795e5.tar.bz2
advent-of-code-50ffa7beba18811b74945b762a86da3fd5a795e5.zip
aoc 2024, day 7, part 1
Diffstat (limited to '2024')
-rw-r--r--2024/src/day07.cpp62
1 files changed, 62 insertions, 0 deletions
diff --git a/2024/src/day07.cpp b/2024/src/day07.cpp
new file mode 100644
index 0000000..9b16b76
--- /dev/null
+++ b/2024/src/day07.cpp
@@ -0,0 +1,62 @@
1#include <fstream>
2#include <iostream>
3#include <sstream>
4#include <string>
5#include <tuple>
6#include <vector>
7using namespace std;
8
9vector<tuple<long, vector<long>>>
10read_file(string_view filename)
11{
12 fstream input{ filename };
13
14 vector<tuple<long, vector<long>>> data;
15 for ( string line; getline(input, line); ) {
16 auto pos = line.find(':');
17
18 stringstream str{ line.substr(pos + 1) };
19 data.emplace_back(stol(line.substr(0, pos)), vector<long>{ istream_iterator<long>{ str }, {} });
20 }
21 return data;
22}
23
24bool
25can_evaluated(long first, const vector<long>& values)
26{
27 for ( unsigned long pattern = 0; pattern != (1U << (values.size() - 1)); ++pattern ) {
28 long result = values.at(0);
29 for ( size_t idx = 1; idx < values.size(); ++idx ) {
30 if ( (pattern & (1U << (idx - 1))) == 0 ) {
31 result += values.at(idx);
32 }
33 else {
34 result *= values.at(idx);
35 }
36 }
37 if ( first == result ) {
38 return true;
39 }
40 }
41 return false;
42}
43
44void
45part1(const vector<tuple<long, vector<long>>>& data)
46{
47 long sum = 0;
48 for ( const auto& [first, values]: data ) {
49 if ( can_evaluated(first, values) ) {
50 sum += first;
51 }
52 }
53 cout << sum << endl;
54}
55
56int
57main()
58{
59 auto data = read_file("data/day07.txt");
60
61 part1(data);
62}