diff options
Diffstat (limited to 'src/2022/day1/aoc.cpp')
-rw-r--r-- | src/2022/day1/aoc.cpp | 57 |
1 files changed, 57 insertions, 0 deletions
diff --git a/src/2022/day1/aoc.cpp b/src/2022/day1/aoc.cpp index 0f036d2..d8175d7 100644 --- a/src/2022/day1/aoc.cpp +++ b/src/2022/day1/aoc.cpp @@ -1,2 +1,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)}; +} + +} |