From 50b228ef89d275b489eb023557c07b5e6cb0370e Mon Sep 17 00:00:00 2001 From: Thomas Schmucker Date: Mon, 4 Dec 2023 20:22:10 +0100 Subject: Lösung für Tag4 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- makefile | 3 +- src/day04.cpp | 116 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 118 insertions(+), 1 deletion(-) create mode 100644 src/day04.cpp diff --git a/makefile b/makefile index 9d0c4c9..7643188 100644 --- a/makefile +++ b/makefile @@ -2,7 +2,8 @@ include config.mk all: bin/day01 \ bin/day02 \ - bin/day03 + bin/day03 \ + bin/day04 bin/%: src/%.cpp | bin c++ $(CPPFLAGS) $^ -o $@ diff --git a/src/day04.cpp b/src/day04.cpp new file mode 100644 index 0000000..8afcb2c --- /dev/null +++ b/src/day04.cpp @@ -0,0 +1,116 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +vector +read_file(string_view filename) +{ + fstream input{ filename }; + vector data; + + for ( string line; getline(input, line); ) { + data.emplace_back(line); + } + + return data; +} + +vector +split(const string& line, char sep) +{ + vector parts{}; + stringstream input{ line }; + + for ( string part; getline(input, part, sep); ) { + parts.emplace_back(part); + } + + return parts; +} + +template +Container +read_ints(const string& line) +{ + Container container{}; + stringstream input{ line }; + + for ( typename Container::value_type value; input >> value; ) { + container.emplace(value); + } + + return container; +} + +vector +build_data_set() +{ + const auto lines = read_file("data/day04.txt"); + vector values{}; + + for ( const auto& line: lines ) { + const auto cards = split(line, ':'); + const auto numbers = split(cards[1], '|'); + + const auto winning_numbers = read_ints>(numbers[0]); + const auto card_numbers = read_ints>(numbers[1]); + + auto count = 0U; + for ( auto number: winning_numbers ) { + if ( card_numbers.contains(number) ) { + ++count; + } + } + values.emplace_back(count); + } + + return values; +} + +void +pass1() +{ + auto sum = 0U; + for ( auto value: build_data_set() ) { + if ( value != 0 ) { + sum += (1U << (value - 1)); + } + } + + cout << sum << endl; +} + +void +pass2() +{ + const auto values = build_data_set(); + auto count = 0U; + + function process = [&](size_t start, size_t end) -> void { + for ( ; start != end; ++start ) { + auto value = values[start]; + + ++count; + + process(start + 1, start + value + 1); + } + }; + + process(0, values.size()); + + cout << count << endl; +} + +int +main() +{ + pass1(); + pass2(); +} -- cgit v1.3