From e182df9e4daf4968750f1414853f4aa1a1e94b15 Mon Sep 17 00:00:00 2001 From: Thomas Schmucker Date: Sat, 9 Dec 2023 09:08:34 +0100 Subject: Lösung für Tag 8 MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- src/day08.cpp | 110 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 110 insertions(+) create mode 100644 src/day08.cpp (limited to 'src') diff --git a/src/day08.cpp b/src/day08.cpp new file mode 100644 index 0000000..3e1b6c9 --- /dev/null +++ b/src/day08.cpp @@ -0,0 +1,110 @@ +#include +#include +#include +#include +#include +#include +using namespace std; + +struct Generator { + explicit Generator(string_view init) + : values_(init) + , iter_(values_.begin()) + + { + } + + size_t next() + { + size_t gen = (*iter_ == 'L') ? 0 : 1; + + ++iter_; + if ( iter_ == values_.end() ) { + iter_ = values_.begin(); + } + + return gen; + } + + string values_; + string::iterator iter_; +}; + +void +part1() +{ + fstream input{ "data/day08.txt" }; + + string line; + getline(input, line); + + Generator generator{ line }; + + map> puzzle; + + const regex pattern{ R"((.*) = \((.*), (.*)\))" }; + while ( getline(input, line) ) { + if ( line.empty() ) { + continue; + } + + smatch sub_match; + if ( regex_search(line, sub_match, pattern) ) { + puzzle[sub_match[1]] = { sub_match[2], sub_match[3] }; + } + } + + auto counter = 0; + for ( string str{ "AAA" }; str != "ZZZ"; str = puzzle[str][generator.next()] ) { + ++counter; + } + cout << counter << endl; +} + +void +part2() +{ + fstream input{ "data/day08.txt" }; + + string firstline; + getline(input, firstline); + + map> puzzle; + + const regex pattern{ R"((.*) = \((.*), (.*)\))" }; + for ( string line; getline(input, line); ) { + if ( line.empty() ) { + continue; + } + + smatch sub_match; + if ( regex_search(line, sub_match, pattern) ) { + puzzle[sub_match[1]] = { sub_match[2], sub_match[3] }; + } + } + + auto value = 1L; + for ( const auto& entry: puzzle ) { + if ( entry.first[2] != 'A' ) { + continue; + } + + Generator generator{ firstline }; + + auto counter = 0L; + + for ( string str{ entry.first }; str[2] != 'Z'; str = puzzle[str][generator.next()] ) { + ++counter; + } + + value = lcm(value, counter); + } + cout << value << endl; +} + +int +main() +{ + part1(); + part2(); +} -- cgit v1.3