diff options
author | kaiwu <kaiwu2004@gmail.com> | 2022-12-02 10:33:00 +0800 |
---|---|---|
committer | kaiwu <kaiwu2004@gmail.com> | 2022-12-02 10:33:00 +0800 |
commit | 6ae048cc3a3ea6e46db3ed70e744238899799bed (patch) | |
tree | 896112e714b5d7c8d426b99ad73453a657af59ce | |
parent | 91b8c863d02195ccdf448a0cd6baee633a6a155d (diff) | |
download | advent-of-code-6ae048cc3a3ea6e46db3ed70e744238899799bed.tar.gz advent-of-code-6ae048cc3a3ea6e46db3ed70e744238899799bed.zip |
2022 day1
-rw-r--r-- | src/2022/day1/aoc.cpp | 57 | ||||
-rw-r--r-- | src/2022/day1/aoc.h | 1 | ||||
-rw-r--r-- | src/2022/day1/input0 | 14 | ||||
-rw-r--r-- | test/test_2022.cpp | 5 |
4 files changed, 76 insertions, 1 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)}; +} + +} diff --git a/src/2022/day1/aoc.h b/src/2022/day1/aoc.h index 9f37d32..9be4ec5 100644 --- a/src/2022/day1/aoc.h +++ b/src/2022/day1/aoc.h @@ -2,4 +2,5 @@ #include "common.h" namespace aoc2022 { +std::pair<int, int> day1(line_view file); } diff --git a/src/2022/day1/input0 b/src/2022/day1/input0 new file mode 100644 index 0000000..2094f91 --- /dev/null +++ b/src/2022/day1/input0 @@ -0,0 +1,14 @@ +1000 +2000 +3000 + +4000 + +5000 +6000 + +7000 +8000 +9000 + +10000 diff --git a/test/test_2022.cpp b/test/test_2022.cpp index dbc8c3b..e9c14cc 100644 --- a/test/test_2022.cpp +++ b/test/test_2022.cpp @@ -3,5 +3,8 @@ #include <stdio.h> TEST_CASE("Calorie Counting", "[2022]") { - // line_view lv = load_file("../src/2022/day1/input"); + line_view lv = load_file("../src/2022/day1/input"); + auto p = aoc2022::day1(lv); + REQUIRE(69693 == p.first); + REQUIRE(200945 == p.second); } |