aboutsummaryrefslogtreecommitdiff
path: root/src/2017/day12/aoc.cpp
blob: 0323e71fc8ca904973a4abd57b880c8eac5df668 (plain)
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
#include "aoc.h"

namespace aoc2017 {

static void get_number(const char** pp, int* d) {
  const char* p = *pp;
  while (*p >= '0' && *p <= '9') {
    *d = *d * 10 + *p - '0';
    p++;
  }
  *pp = p;
}

struct record12 {
  int ns[10] = {0};
  bool connected = false;

  void print() const noexcept {
    for (auto n : ns) {
      printf("%d ", n);
    }
    printf("\n");
  }

  record12(line_view lv) {
    const char* p = lv.line;
    int i{0};
    while (p < lv.line + lv.length) {
      if (*p >= '0' && *p <= '9') {
        get_number(&p, &ns[i++]);
      }
      p++;
    }
  }
};

void mark_connected(size_t i, std::vector<record12>& rs, int* total) {
  auto& r = rs[i];
  if (!r.connected) {
    *total += 1;
    r.connected = true;
    for (int x = 1; x < 10; x++) {
      if (r.ns[x] > 0) {
        mark_connected(r.ns[x], rs, total);
      }
    }
  }
}

std::pair<int64_t, int64_t> day12(line_view file) {
  std::vector<record12> rs;
  per_line(file, [&rs](line_view lv) {
    rs.emplace_back(lv);
    return true;
  });

  int total{0};
  mark_connected(0, rs, &total);
  int t0 = total;
  int t1 = 1;

  for (size_t i = 1; i < rs.size() && total < (int)rs.size(); i++) {
    int tx = total;
    mark_connected(i, rs, &total);
    if (total > tx) {
      t1 += 1;
    }
  }

  return {t0, t1};
}
} // namespace aoc2017