diff options
Diffstat (limited to '2022/src')
| -rw-r--r-- | 2022/src/day01.cpp | 73 |
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> | ||
| 7 | using namespace std; | ||
| 8 | |||
| 9 | string | ||
| 10 | read_file(string_view filename) | ||
| 11 | { | ||
| 12 | fstream input{ filename }; | ||
| 13 | return { istreambuf_iterator<char>{ input }, {} }; | ||
| 14 | } | ||
| 15 | |||
| 16 | vector<string> | ||
| 17 | split(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 | |||
| 36 | vector<long> | ||
| 37 | split(const string& line) | ||
| 38 | { | ||
| 39 | stringstream input{ line }; | ||
| 40 | return { istream_iterator<long>(input), {} }; | ||
| 41 | } | ||
| 42 | |||
| 43 | void | ||
| 44 | part1(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 | |||
| 54 | void | ||
| 55 | part2(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 | |||
| 66 | int | ||
| 67 | main() | ||
| 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 | } | ||
