aboutsummaryrefslogtreecommitdiff
path: root/src/2022/day13/aoc.cpp
blob: 070f0cd954398071d056e4457b91d53d87ee38d6 (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
#include "aoc.h"
#include <iostream>
#include <algorithm>


namespace aoc2022 {
struct pkt {
  packet* p;
  size_t i;
};

std::pair<int, int> find(const std::vector<pkt>& ps) {
  size_t s1 = ps.size() - 1;
  size_t s2 = ps.size() - 2;
  size_t a{0}, b{0};
  for(size_t i = 0; i < ps.size(); i++) {
    if (ps[i].i == s1) a = i + 1;
    if (ps[i].i == s2) b = i + 1;
    // printf("%zu %zu:", i + 1, ps[i].i);
    // ps[i].p->print(0);
    // printf("\n");
  }
  // printf("%zu %zu\n", a, b);
  return {a, b};
}

std::pair<int, int> day13(line_view file) {
  int count{0};
  int pair{0};


  std::vector<pkt> all;
  packet* ps[2] = {nullptr, nullptr};
  per_line(file, [&pair, &count, &ps, &all](line_view lv){
    if (lv.length > 1) {
      int i = pair % 2;
      packet* pkt = new packet;
      ps[i] = pkt;
      const char* p = lv.line;
      packet::load(&p, &ps[i]);
      all.push_back({pkt, (size_t) pair});
      if (i == 1 && *(ps[0]) < *(ps[1])) {
        // printf("group[%d] is in right order\n", pair/2 + 1);
        count += pair / 2 + 1;
      }
      pair += 1;
    }
    return true;
  });

  std::sort(all.begin(), all.end(), [](const pkt& p1, const pkt& p2){
    return *(p1.p) < *(p2.p); 
  });

  auto p = find(all);

  return {count, p.first * p.second};
}
}