diff options
author | kaiwu <kaiwu2004@gmail.com> | 2022-04-03 23:39:35 +0800 |
---|---|---|
committer | kaiwu <kaiwu2004@gmail.com> | 2022-04-03 23:39:35 +0800 |
commit | ad2f9dbe34ec79c0b9c23fea2ec5d963e9c05d5f (patch) | |
tree | b337747ac2477c7a6769aeacad517d41402d6dfe /src/2016/day1/aoc.h | |
parent | cc9343b7b24141a0d79e1e85969df9a7446585f8 (diff) | |
download | advent-of-code-ad2f9dbe34ec79c0b9c23fea2ec5d963e9c05d5f.tar.gz advent-of-code-ad2f9dbe34ec79c0b9c23fea2ec5d963e9c05d5f.zip |
filter tests by year
Diffstat (limited to 'src/2016/day1/aoc.h')
-rw-r--r-- | src/2016/day1/aoc.h | 59 |
1 files changed, 56 insertions, 3 deletions
diff --git a/src/2016/day1/aoc.h b/src/2016/day1/aoc.h index abcafe0..b6e556e 100644 --- a/src/2016/day1/aoc.h +++ b/src/2016/day1/aoc.h @@ -2,6 +2,7 @@ #include "common.h" #include <algorithm> #include <math.h> +#include <set> #include <vector> namespace aoc2016 { @@ -25,6 +26,7 @@ struct position { int x; int y; + bool operator<(const position& p) const noexcept { return x < p.x ? true : (x > p.x ? false : y < p.y); } int blocks(position p) const noexcept { return abs(p.x - x) + abs(p.y - y); } position move(instruction i) const noexcept { @@ -52,13 +54,64 @@ struct position { return next; } - position move(const std::vector<instruction>& is) const noexcept { + std::vector<position> line(position p1, position p2) const noexcept { + std::vector<position> ps; + auto copyx = [&p1, &p2, &ps](int x) { + if (x > 0) { + for (int i = p1.x; i < p2.x; i++) { + ps.push_back({p2.b, i, p1.y}); + } + } + if (x < 0) { + for (int i = p1.x; i > p2.x; i--) { + ps.push_back({p2.b, i, p1.y}); + } + } + }; + auto copyy = [&p1, &p2, &ps](int y) { + if (y > 0) { + for (int i = p1.y; i < p2.y; i++) { + ps.push_back({p2.b, p1.x, i}); + } + } + if (y < 0) { + for (int i = p1.y; i > p2.y; i--) { + ps.push_back({p2.b, p1.x, i}); + } + } + }; + copyx(p2.x - p1.x); + copyy(p2.y - p1.y); + return ps; + } + + void cross(position p1, position p2, position* first, bool* found) const noexcept { + static std::set<position> ps = {}; + if (!(*found)) { + auto v = line(p1, p2); + for (size_t i = 0; i < v.size(); i++) { + // printf("%d %d %d\n", int(v[i].b), v[i].x, v[i].y); + auto p = ps.insert(v[i]); + if (!p.second) { + *found = true; + *first = *p.first; + return; + } + } + } + } + + position move(const std::vector<instruction>& is, position* first, bool* found) const noexcept { position next = *this; - std::for_each(is.begin(), is.end(), [&next](const instruction& i) { next = next.move(i); }); + std::for_each(is.begin(), is.end(), [&next, first, found, this](const instruction& i) { + position prev = next; + next = next.move(i); + cross(prev, next, first, found); + }); return next; } }; -int day1(line_view); +std::pair<int, int> day1(line_view); } // namespace aoc2016 |