aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorkaiwu <kaiwu2004@gmail.com>2022-12-02 10:33:00 +0800
committerkaiwu <kaiwu2004@gmail.com>2022-12-02 10:33:00 +0800
commit6ae048cc3a3ea6e46db3ed70e744238899799bed (patch)
tree896112e714b5d7c8d426b99ad73453a657af59ce /src
parent91b8c863d02195ccdf448a0cd6baee633a6a155d (diff)
downloadadvent-of-code-6ae048cc3a3ea6e46db3ed70e744238899799bed.tar.gz
advent-of-code-6ae048cc3a3ea6e46db3ed70e744238899799bed.zip
2022 day1
Diffstat (limited to 'src')
-rw-r--r--src/2022/day1/aoc.cpp57
-rw-r--r--src/2022/day1/aoc.h1
-rw-r--r--src/2022/day1/input014
3 files changed, 72 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)};
+}
+
+}
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