aboutsummaryrefslogtreecommitdiff
path: root/2022
diff options
context:
space:
mode:
authorThomas Schmucker <ts@its1.de>2024-04-23 23:30:00 +0200
committerThomas Schmucker <ts@its1.de>2024-04-23 23:30:00 +0200
commit5b9d1245f073f858e81b5a476463a948111a8a73 (patch)
treed7d707a0f5a72ece8967a2d40600a02c38483959 /2022
parentfd8bd06069ff4b461de131f07b72316e7955f37d (diff)
downloadadvent-of-code-5b9d1245f073f858e81b5a476463a948111a8a73.tar.gz
advent-of-code-5b9d1245f073f858e81b5a476463a948111a8a73.tar.bz2
advent-of-code-5b9d1245f073f858e81b5a476463a948111a8a73.zip
day01, advent of code 2022
Diffstat (limited to '2022')
-rw-r--r--2022/src/day01.cpp73
1 files changed, 73 insertions, 0 deletions
diff --git a/2022/src/day01.cpp b/2022/src/day01.cpp
new file mode 100644
index 0000000..ece0309
--- /dev/null
+++ b/2022/src/day01.cpp
@@ -0,0 +1,73 @@
1#include <fstream>
2#include <iostream>
3#include <numeric>
4#include <sstream>
5#include <string>
6#include <vector>
7using namespace std;
8
9string
10read_file(string_view filename)
11{
12 fstream input{ filename };
13 return { istreambuf_iterator<char>{ input }, {} };
14}
15
16vector<string>
17split(string_view line, string_view delimiter)
18{
19 string::size_type pos_start = 0;
20 string::size_type pos_end = 0;
21
22 vector<string> result;
23
24 while ( (pos_end = line.find(delimiter, pos_start)) != string::npos ) {
25 result.emplace_back(line.substr(pos_start, pos_end - pos_start));
26 pos_start = pos_end + delimiter.length();
27 }
28
29 if ( pos_start != line.size() ) {
30 result.emplace_back(line.substr(pos_start));
31 }
32
33 return result;
34}
35
36vector<long>
37split(const string& line)
38{
39 stringstream input{ line };
40 return { istream_iterator<long>(input), {} };
41}
42
43void
44part1(const vector<string>& parts)
45{
46 long max_so_far = 0;
47 for ( const auto& part: parts ) {
48 const auto nums = split(part);
49 max_so_far = max(accumulate(begin(nums), end(nums), 0L), max_so_far);
50 }
51 cout << max_so_far << endl;
52}
53
54void
55part2(const vector<string>& parts)
56{
57 vector<long> all;
58 for ( const auto& part: parts ) {
59 const auto nums = split(part);
60 all.emplace_back(accumulate(begin(nums), end(nums), 0L));
61 }
62 sort(begin(all), end(all), greater<>());
63 cout << all[0] + all[1] + all[2] << endl;
64}
65
66int
67main()
68{
69 const auto line = read_file("data/day01.txt");
70 const auto parts = split(line, "\n\n");
71 part1(parts);
72 part2(parts);
73}