From d396dc3221fcf893c885bd9a370b9a30f25b31dd Mon Sep 17 00:00:00 2001 From: Thomas Schmucker Date: Sun, 12 Jan 2025 17:36:26 +0100 Subject: aoc 2016, days 4, 5, 6 --- 2016/src/day04.cpp | 102 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 102 insertions(+) create mode 100644 2016/src/day04.cpp (limited to '2016/src/day04.cpp') diff --git a/2016/src/day04.cpp b/2016/src/day04.cpp new file mode 100644 index 0000000..713b16f --- /dev/null +++ b/2016/src/day04.cpp @@ -0,0 +1,102 @@ +#include +#include +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +vector +split(const string& line, const regex& sep) +{ + return { sregex_token_iterator(line.begin(), line.end(), sep, -1), {} }; +} + +vector, long, string>> +read_file(string_view filename) +{ + fstream input{ filename }; + + vector, long, string>> result; + + for ( string line; getline(input, line); ) { + static const regex sep{ "[\\[\\]-]" }; + + auto parts = split(line, sep); + + auto checksum = parts.at(parts.size() - 1); + parts.pop_back(); + + auto selector = stol(parts.at(parts.size() - 1)); + parts.pop_back(); + + result.emplace_back(parts, selector, checksum); + } + + return result; +} + +void +part1(const vector, long, string>>& data) +{ + long sum = 0; + for ( const auto& [ids, selector, checksum]: data ) { + map counts; + for ( const auto& id: ids ) { + for ( const auto chr: id ) { + ++counts[chr]; + } + } + + set> tops; + for ( const auto& [chr, count]: counts ) { + tops.emplace(-count, chr); + } + + string result; + for ( const auto& [count, chr]: tops ) { + result += chr; + } + + if ( result.starts_with(checksum) ) { + sum += selector; + } + } + cout << sum << endl; +} + +void +part2(const vector, long, string>>& lines) +{ + auto rot = [](string str, int n) { + for ( auto& chr: str ) { + chr = ((chr - 'a' + n) % 26) + 'a'; + } + return str; + }; + + auto is_northpole = [&](const string& str, int n) { + return rot(str, n) == "northpole"; + }; + + for ( const auto& line: lines ) { + const auto& ids = get<0>(line); + const auto selector = get<1>(line); + if ( ranges::any_of(ids, [&](auto& str) { return is_northpole(str, (int) selector); }) ) { + cout << selector << endl; + return; + } + } +} + +int +main() +{ + auto data = read_file("data/day04.txt"); + part1(data); + part2(data); +} -- cgit v1.3