aboutsummaryrefslogtreecommitdiff
path: root/src/2020/day8
diff options
context:
space:
mode:
authorkaiwu <kaiwu2004@gmail.com>2022-05-14 17:39:58 +0800
committerkaiwu <kaiwu2004@gmail.com>2022-05-14 17:39:58 +0800
commit17fe147d01b3522b7f9214b48d738b8e474cbed9 (patch)
treec83b20f5892a3ca4ef2192449a2591004d5b2f17 /src/2020/day8
parent1a9146ae65c309c1c4dafb57a08ffb25c632fa78 (diff)
downloadadvent-of-code-17fe147d01b3522b7f9214b48d738b8e474cbed9.tar.gz
advent-of-code-17fe147d01b3522b7f9214b48d738b8e474cbed9.zip
2020 day8
Diffstat (limited to 'src/2020/day8')
-rw-r--r--src/2020/day8/aoc.cpp48
-rw-r--r--src/2020/day8/aoc.h2
2 files changed, 34 insertions, 16 deletions
diff --git a/src/2020/day8/aoc.cpp b/src/2020/day8/aoc.cpp
index 830141a..6170215 100644
--- a/src/2020/day8/aoc.cpp
+++ b/src/2020/day8/aoc.cpp
@@ -3,31 +3,49 @@
namespace aoc2020 {
-static void run(size_t index, std::vector<code>& cs, int* accumlator) {
- auto& code = cs[index];
- if (code.executed == 0) {
- size_t next = index + 1;
- if (code.type == acc) {
- *accumlator += code.value;
+static int run(size_t index, std::vector<code> cs, int* accumlator) {
+ if (index < cs.size()) {
+ auto& code = cs[index];
+ if (code.executed == 0) {
+ size_t next = index + 1;
+ if (code.type == acc) {
+ *accumlator += code.value;
+ }
+ if (code.type == jmp) {
+ next = index + code.value;
+ }
+ code.executed += 1;
+ return run(next, cs, accumlator);
}
- if (code.type == jmp) {
- next = index + code.value;
- }
- code.executed += 1;
- run(next, cs, accumlator);
+ return 1;
}
+ return 0;
}
-int day8(line_view file) {
+std::pair<int, int> day8(line_view file) {
std::vector<code> cs;
- int accumlator = 0;
+ int acc0 = 0;
per_line(file, [&cs](line_view lv) {
cs.emplace_back(lv);
return true;
});
+ run(0, cs, &acc0);
- run(0, cs, &accumlator);
- return accumlator;
+ auto reset = [](code& c) {
+ c.type = (code_t)(!(int)c.type);
+ };
+ int acc1 = 0;
+ for(auto& code: cs) {
+ if (code.type != acc) {
+ reset(code);
+ acc1 = 0;
+ if (run(0, cs, &acc1) == 0) {
+ break;
+ }
+ reset(code);
+ }
+ }
+ return {acc0, acc1};
}
} // namespace aoc2020
diff --git a/src/2020/day8/aoc.h b/src/2020/day8/aoc.h
index ae2b8ee..b39b124 100644
--- a/src/2020/day8/aoc.h
+++ b/src/2020/day8/aoc.h
@@ -44,6 +44,6 @@ struct code {
}
};
-int day8(line_view);
+std::pair<int, int> day8(line_view);
} // namespace aoc2020