From 5b9d1245f073f858e81b5a476463a948111a8a73 Mon Sep 17 00:00:00 2001 From: Thomas Schmucker Date: Tue, 23 Apr 2024 23:30:00 +0200 Subject: day01, advent of code 2022 --- 2022/src/day01.cpp | 73 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 2022/src/day01.cpp (limited to '2022/src') 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 @@ +#include +#include +#include +#include +#include +#include +using namespace std; + +string +read_file(string_view filename) +{ + fstream input{ filename }; + return { istreambuf_iterator{ input }, {} }; +} + +vector +split(string_view line, string_view delimiter) +{ + string::size_type pos_start = 0; + string::size_type pos_end = 0; + + vector result; + + while ( (pos_end = line.find(delimiter, pos_start)) != string::npos ) { + result.emplace_back(line.substr(pos_start, pos_end - pos_start)); + pos_start = pos_end + delimiter.length(); + } + + if ( pos_start != line.size() ) { + result.emplace_back(line.substr(pos_start)); + } + + return result; +} + +vector +split(const string& line) +{ + stringstream input{ line }; + return { istream_iterator(input), {} }; +} + +void +part1(const vector& parts) +{ + long max_so_far = 0; + for ( const auto& part: parts ) { + const auto nums = split(part); + max_so_far = max(accumulate(begin(nums), end(nums), 0L), max_so_far); + } + cout << max_so_far << endl; +} + +void +part2(const vector& parts) +{ + vector all; + for ( const auto& part: parts ) { + const auto nums = split(part); + all.emplace_back(accumulate(begin(nums), end(nums), 0L)); + } + sort(begin(all), end(all), greater<>()); + cout << all[0] + all[1] + all[2] << endl; +} + +int +main() +{ + const auto line = read_file("data/day01.txt"); + const auto parts = split(line, "\n\n"); + part1(parts); + part2(parts); +} -- cgit v1.3