From 0d7d45995a34e3bfaefa7bb90eb4c1314acd027e Mon Sep 17 00:00:00 2001 From: Orfeas <38209077+0xfea5@users.noreply.github.com> Date: Wed, 27 Aug 2025 14:42:06 +0300 Subject: day02: done --- day02/solution.cpp | 81 ++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 day02/solution.cpp (limited to 'day02/solution.cpp') diff --git a/day02/solution.cpp b/day02/solution.cpp new file mode 100644 index 0000000..e4f47b8 --- /dev/null +++ b/day02/solution.cpp @@ -0,0 +1,81 @@ +#include +#include +#include +#include +#include +#include +#include +#include + +namespace ranges = std::ranges; +namespace views = std::views; + +const auto parse_input() { + std::vector> result; + for (std::string s; std::getline(std::cin, s);) { + std::stringstream ss{s}; + std::vector row; + for (int l; ss >> l;) { + row.push_back(l); + } + result.push_back(row); + } + return result; +} + +bool safe_report(const auto &report) { + assert(report.size() > 0); + std::vector _diffs(report.size()); + std::adjacent_difference(report.begin(), report.end(), _diffs.begin()); + + // The first diff is from 0 (zero) to the first layer, so we ignore it + const auto diffs = ranges::subrange(_diffs.begin() + 1, _diffs.end()); + const bool ascending = std::count_if(diffs.begin(), diffs.end(), [](int d) { + return d > 0; + }) > (diffs.size() / 2); + + const bool safe = ranges::all_of(diffs, [ascending](int d) { + const bool bounded = (1 <= std::abs(d) and std::abs(d) <= 3); + const bool monotonic = ((d > 0 and ascending) or (d < 0 and not ascending)); + return monotonic and bounded; + }); + return safe; +} + +void part1(const auto &input) { + int answer{0}; + + for (const auto &report : input) { + if (safe_report(report)) { + ++answer; + } + } + + std::println("{}", answer); +} + +void part2(const auto &input) { + int answer{0}; + for (const auto &report : input) { + if (ranges::any_of(views::iota(size_t(0), report.size()), [&report](size_t i) { + return safe_report(views::concat(report | views::take(i), + report | views::drop(i + 1))); + })) { + ++answer; + } + } + std::println("{}", answer); +} + +int main() { + const auto input = parse_input(); + +#ifndef NO_PART1 + part1(input); +#endif + +#ifndef NO_PART2 + part2(input); +#endif + return 0; +} -- cgit v1.2.3