aboutsummaryrefslogtreecommitdiff
path: root/src/2016/day1/aoc.h
diff options
context:
space:
mode:
Diffstat (limited to 'src/2016/day1/aoc.h')
-rw-r--r--src/2016/day1/aoc.h59
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