aboutsummaryrefslogtreecommitdiff
path: root/src/2022/day1/aoc.cpp
blob: d8175d79630ae4af4248390b46bf91e6949bbfe0 (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
#include "aoc.h"
#include <vector>
#include <algorithm>

namespace aoc2022 {

struct Calory {
  line_view lv;
  int total;
};

Calory get_calory(const char* p0, const char* p1) {
  const char* p = p0;
  int d{0};
  int total{0};
  while(p < p1) {
    if (*p >= '0' && *p <= '9') {
      d = d * 10 + *p - '0';
    }
    else {
      total += d;
      d = 0;
    }
    p++;
  }
  total += d;
  return {line_view{p0, p1}, total};
}

int top3(const std::vector<Calory>& cs) {
  return cs[0].total + cs[1].total + cs[2].total;
}
 
std::pair<int, int> day1(line_view file) {
  std::vector<Calory> cs;
  int max{0};

  const char* p0 = file.line;
  const char* p1 = p0;
  const char* p2 = p1 + file.length;

  while (p1 < p2) {
    if (*p1 == '\n' && (p1 + 1 == p2 || *(p1 + 1) == '\n')) {
      Calory c = get_calory(p0, p1);
      // printf("%d \n", c.total);
      cs.push_back(c);
      if (max < c.total) {
        max = c.total;
      }
      p0 = p1 + 2;
    }
    p1++;
  }
  std::sort(cs.begin(), cs.end(), [](const Calory& c1, const Calory& c2){return c1.total > c2.total;});
  return {max,top3(cs)};
}

}