aboutsummaryrefslogtreecommitdiff
path: root/2022/src
diff options
context:
space:
mode:
authorThomas Schmucker <ts@its1.de>2024-04-28 10:40:25 +0200
committerThomas Schmucker <ts@its1.de>2024-04-28 10:40:25 +0200
commitfcf4708efd24461ea71e3086d5fbd672d53621d2 (patch)
tree8ed637ef984a93a6b9d5b9323c5f1f8ee9d6608a /2022/src
parent1088bfbda97eb89bf55fd7cd171726eb7f6ea71f (diff)
downloadadvent-of-code-fcf4708efd24461ea71e3086d5fbd672d53621d2.tar.gz
advent-of-code-fcf4708efd24461ea71e3086d5fbd672d53621d2.tar.bz2
advent-of-code-fcf4708efd24461ea71e3086d5fbd672d53621d2.zip
day 3, advent of code 2022
Diffstat (limited to '2022/src')
-rw-r--r--2022/src/day03.cpp105
1 files changed, 105 insertions, 0 deletions
diff --git a/2022/src/day03.cpp b/2022/src/day03.cpp
new file mode 100644
index 0000000..773ccf6
--- /dev/null
+++ b/2022/src/day03.cpp
@@ -0,0 +1,105 @@
1#include <algorithm>
2#include <fstream>
3#include <iostream>
4#include <iterator>
5#include <map>
6#include <set>
7#include <string>
8#include <vector>
9using namespace std;
10
11set<char>
12make_unique(string_view str)
13{
14 return { begin(str), end(str) };
15}
16
17map<char, int>
18make_lookup()
19{
20 map<char, int> lookup;
21 for ( int i = 0; i != 26; ++i ) {
22 lookup[char('a' + i)] = i + 1;
23 lookup[char('A' + i)] = i + 27;
24 }
25 return lookup;
26}
27
28vector<tuple<set<char>, set<char>>>
29read_file(string_view filename)
30{
31 fstream input{ filename };
32 vector<tuple<set<char>, set<char>>> data;
33
34 for ( string line; getline(input, line); ) {
35 const auto lhs = line.substr(0, line.length() / 2);
36 const auto rhs = line.substr(line.length() / 2);
37 data.emplace_back(make_unique(lhs), make_unique(rhs));
38 }
39
40 return data;
41}
42
43vector<string>
44read_file2(string_view filename)
45{
46 fstream input{ filename };
47 vector<string> data;
48
49 for ( string line; getline(input, line); ) {
50 data.emplace_back(line);
51 }
52
53 return data;
54}
55
56void
57part1(const vector<tuple<set<char>, set<char>>>& data)
58{
59 auto lookup = make_lookup();
60
61 int sum = 0;
62 for ( const auto& [lhs, rhs]: data ) {
63 string intersection;
64 set_intersection(begin(lhs), end(lhs), begin(rhs), end(rhs), back_inserter(intersection));
65
66 sum += lookup[intersection[0]];
67 }
68 cout << sum << endl;
69}
70
71void
72part2(const vector<string>& data)
73{
74 auto lookup = make_lookup();
75
76 int sum = 0;
77 for ( size_t i = 0; i < data.size(); i += 3 ) {
78 map<char, int> count;
79
80 const array<set<char>, 3> sets = { make_unique(data[i]),
81 make_unique(data[i + 1]),
82 make_unique(data[i + 2]) };
83
84 for ( const auto& set: sets ) {
85 for ( const auto chr: set ) {
86 count[chr]++;
87 }
88 }
89
90 for ( const auto& [key, value]: count ) {
91 if ( value == 3 ) {
92 sum += lookup[key];
93 }
94 }
95 }
96 cout << sum << endl;
97}
98
99int
100main()
101{
102 const auto* const filename = "data/day03.txt";
103 part1(read_file(filename));
104 part2(read_file2(filename));
105}