summaryrefslogtreecommitdiffstats
path: root/day02/solution.cpp
blob: e4f47b83ff46e7f068accd5c3d9a9ec0dcb3b82c (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
#include <numeric>
#include <cassert>
#include <print>
#include <iostream>
#include <vector>
#include <ranges>
#include <algorithm>
#include <sstream>

namespace ranges = std::ranges;
namespace views = std::views;

const auto parse_input() {
  std::vector<std::vector<int>> result;
  for (std::string s; std::getline(std::cin, s);) {
    std::stringstream ss{s};
    std::vector<int> 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<int> _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;
}