aboutsummaryrefslogtreecommitdiff
path: root/src/2017/day9/aoc.cpp
blob: 9047aefefb430b479ce885c3e9fe5b34d8600d01 (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
#include "aoc.h"
#include <stack>

namespace aoc2017 {

static void take(const char* p, std::stack<char>& gs, int* t) {
  if (*p == '{') {
    gs.push(*p);
  }
  if (*p == '}') {
    *t += gs.size();
    gs.pop();
  }
}

static bool is_valid(const char* p, std::stack<char>& g, int* t) {
  if (g.empty()) {
    if (*p == '!') {
      g.push(*p);
    }
    if (*p == '<') {
      g.push(*p);
    }
  } else {
    if (g.top() == '!') {
      g.pop();
    } else {
      *t += 1;
      if (*p == '>') {
        g.pop();
        *t -= 1;
      }
      if (*p == '!') {
        g.push(*p);
        *t -= 1;
      }
    }
  }

  return g.empty();
}

std::pair<int, int> day9(line_view file) {
  int t0{0};
  int t1{0};
  std::stack<char> gs;
  std::stack<char> gv;
  const char* p = file.line;
  while (p < file.line + file.length) {
    if (is_valid(p, gv, &t1)) {
      take(p, gs, &t0);
    }
    p++;
  }
  return {t0, t1};
}

} // namespace aoc2017