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 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ makefile | 7 +++++- 2 files changed, 79 insertions(+), 1 deletion(-) create mode 100644 2022/src/day01.cpp 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); +} diff --git a/makefile b/makefile index e1318c1..494ced4 100644 --- a/makefile +++ b/makefile @@ -1,6 +1,7 @@ include config.mk all: $(patsubst 2020/src/%.cpp,2020/bin/%,$(wildcard 2020/src/*.cpp)) \ + $(patsubst 2022/src/%.cpp,2022/bin/%,$(wildcard 2022/src/*.cpp)) \ $(patsubst 2023/src/%.cpp,2023/bin/%,$(wildcard 2023/src/*.cpp)) %/bin: @@ -10,6 +11,10 @@ all: $(patsubst 2020/src/%.cpp,2020/bin/%,$(wildcard 2020/src/*.cpp)) \ 2020/bin/%: 2020/src/%.cpp | 2020/bin c++ $(CPPFLAGS) $^ -o $@ +# 2022 +2022/bin/%: 2022/src/%.cpp | 2022/bin + c++ $(CPPFLAGS) $^ -o $@ + # 2023 2023/bin/%: 2023/src/%.cpp | 2023/bin c++ $(CPPFLAGS) $^ -o $@ @@ -18,6 +23,6 @@ all: $(patsubst 2020/src/%.cpp,2020/bin/%,$(wildcard 2020/src/*.cpp)) \ c++ $(CPPFLAGS) -Wno-sign-conversion -I/usr/local/include $^ -L/usr/local/lib -lz3 -o $@ clean: - rm -rf 2020/bin 2023/bin + rm -rf 2020/bin 2022/bin 2023/bin .PHONY: all clean -- cgit v1.3