From 8a431820b0b360b9a7c9e086cac05935bee8275a Mon Sep 17 00:00:00 2001 From: Bert Peters Date: Wed, 4 Dec 2019 07:59:18 +0100 Subject: [PATCH] Implement day 04. --- 2019/inputs/04.txt | 1 + 2019/src/day04.cpp | 88 ++++++++++++++++++++++++++++++++++++++++++++-- 2 files changed, 87 insertions(+), 2 deletions(-) create mode 100644 2019/inputs/04.txt diff --git a/2019/inputs/04.txt b/2019/inputs/04.txt new file mode 100644 index 0000000..9e35a59 --- /dev/null +++ b/2019/inputs/04.txt @@ -0,0 +1 @@ +197487-673251 diff --git a/2019/src/day04.cpp b/2019/src/day04.cpp index c9f113f..a8dd0b2 100644 --- a/2019/src/day04.cpp +++ b/2019/src/day04.cpp @@ -1,10 +1,94 @@ #include +#include #include "days.hpp" +namespace { + constexpr bool is_valid_pass(int num) { + bool has_double = false; + int prev = 11; + + for (; num != 0; num /= 10) { + int digit = num % 10; + + if (digit == prev) { + has_double = true; + } + + if (digit > prev) { + return false; + } + + prev = digit; + } + + return has_double; + } + + constexpr bool is_valid_pass2(int num) { + int prev = 11; + bool has_double = false; + int run = 1; + + for (; num != 0; num /= 10) { + int digit = num % 10; + + if (digit == prev) { + ++run; + } else { + if (run == 2) { + has_double = true; + } + run = 1; + } + + if (digit > prev) { + return false; + } + + prev = digit; + } + + return has_double || run == 2; + } + + std::pair read_input(std::istream& input) { + int a, b; + input >> a; + input.ignore(); + input >> b; + + return {a, b}; + } +} + void aoc2019::day04_part1(std::istream &input, std::ostream &output) { - output << "Not implemented\n"; + auto [start_range, end_range] = read_input(input); + + int num_valid = 0; + for (; start_range <= end_range; ++start_range) { + num_valid += is_valid_pass(start_range); + } + + output << num_valid << std::endl; } void aoc2019::day04_part2(std::istream &input, std::ostream &output) { - output << "Not implemented\n"; + auto [start_range, end_range] = read_input(input); + + int num_valid = 0; + for (; start_range <= end_range; ++start_range) { + num_valid += is_valid_pass2(start_range); + } + + output << num_valid << std::endl; } + +// Poor man's unit tests +static_assert(is_valid_pass(122345)); +static_assert(is_valid_pass(111111)); +static_assert(!is_valid_pass(223450)); +static_assert(!is_valid_pass(123678)); + +static_assert(is_valid_pass2(112233)); +static_assert(!is_valid_pass2(123444)); +static_assert(is_valid_pass2(111122));