From 8c96639ec1f6757570510fc27f1c5fabece35eaf Mon Sep 17 00:00:00 2001 From: Thomas Schmucker Date: Sun, 16 Nov 2025 13:23:34 +0100 Subject: aoc 2018, days 1-11 --- 2018/src/day02.cpp | 87 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 87 insertions(+) create mode 100644 2018/src/day02.cpp (limited to '2018/src/day02.cpp') diff --git a/2018/src/day02.cpp b/2018/src/day02.cpp new file mode 100644 index 0000000..5dc6c7f --- /dev/null +++ b/2018/src/day02.cpp @@ -0,0 +1,87 @@ +#include +#include +#include +#include +#include +#include +#include + +using namespace std; + +namespace { + +vector +read_lines(const filesystem::path& filename) +{ + ifstream file{ filename }; + vector lines; + + for ( string line; getline(file, line); ) { + lines.emplace_back(line); + } + + return lines; +} + +void +part1(const vector& lines) +{ + int twos = 0; + int threes = 0; + for ( const auto& line: lines ) { + map foo; + for ( const auto chr: line ) { + foo[chr]++; + } + + set counts; + for ( const auto& [chr, count]: foo ) { + counts.insert(count); + } + + if ( counts.contains(2) ) { + ++twos; + } + if ( counts.contains(3) ) { + ++threes; + } + } + cout << "Part 1: " << twos * threes << '\n'; +} + +void +part2(const vector& lines) +{ + for ( size_t i = 0; i != lines.size(); ++i ) { + for ( size_t j = i + 1; j != lines.size(); ++j ) { + const auto& lhs = lines.at(i); + const auto& rhs = lines.at(j); + + if ( lhs.length() != rhs.length() ) { + throw runtime_error("invalid data"); + } + + string result; + for ( size_t k = 0; k != lhs.length(); ++k ) { + if ( lhs[k] == rhs[k] ) { + result += lhs[k]; + } + } + + if ( result.length() + 1 == lhs.length() ) { + cout << "Part 2: " << result << '\n'; + return; + } + } + } +} + +} // namespace + +int +main() +{ + auto lines = read_lines("data/day02.txt"); + part1(lines); + part2(lines); +} -- cgit v1.3