From a6c923706a0447e65c3b0b2644727367494d3947 Mon Sep 17 00:00:00 2001 From: Thomas Schmucker Date: Tue, 2 Dec 2025 19:58:55 +0100 Subject: aoc 2025, day 2 --- 2025/src/day02.cpp | 115 +++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 115 insertions(+) create mode 100644 2025/src/day02.cpp diff --git a/2025/src/day02.cpp b/2025/src/day02.cpp new file mode 100644 index 0000000..1d17cd9 --- /dev/null +++ b/2025/src/day02.cpp @@ -0,0 +1,115 @@ +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +namespace { + +vector +split(const string& line, char sep) +{ + istringstream strm{ line }; + vector parts; + + for ( string part; getline(strm, part, sep); ) { + parts.emplace_back(part); + } + return parts; +} + +vector> +read_file(const filesystem::path& filename) +{ + ifstream file{ filename }; + string line; + getline(file, line); + + vector> ranges; + for ( const auto& part: split(line, ',') ) { + const auto range = split(part, '-'); + ranges.emplace_back(stol(range.at(0)), stol(range.at(1))); + } + return ranges; +} + +long +accumulate_invalids(const vector>& ranges, const function& is_invalid) +{ + long sum = 0; + for ( const auto [from, to]: ranges ) { + for ( auto i = from; i <= to; ++i ) { + if ( is_invalid(i) ) { + sum += i; + } + } + } + return sum; +} + +void +part1(const vector>& ranges) +{ + auto is_invalid = [](long num) { + const auto str = to_string(num); + const auto len = str.length(); + + if ( len % 2 == 1 ) { + return false; + } + + const auto half = len / 2; + + for ( size_t i = 0; i != half; ++i ) { + if ( str[i] != str[i + half] ) { + return false; + } + } + + return true; + }; + + cout << "Part 1: " << accumulate_invalids(ranges, is_invalid) << '\n'; +} + +void +part2(const vector>& ranges) +{ + auto is_invalid = [](long num) { + const auto str = to_string(num); + const auto len = str.length(); + const auto half = len / 2; + + for ( size_t i = 1; i <= half; ++i ) { + if ( len % i != 0 ) { + continue; + } + + string pattern; + while ( pattern.length() != len ) { + pattern += str.substr(0, i); + } + if ( pattern == str ) { + return true; + } + } + + return false; + }; + + cout << "Part 2: " << accumulate_invalids(ranges, is_invalid) << '\n'; +} + +} // namespace + +int +main() +{ + auto ranges = read_file("data/day02.txt"); + part1(ranges); + part2(ranges); +} -- cgit v1.3