summary refs log tree commit diff homepage
path: root/2019
diff options
context:
space:
mode:
authorJune McEnroe <june@causal.agency>2019-12-03 02:02:07 -0500
committerJune McEnroe <june@causal.agency>2019-12-03 02:02:07 -0500
commitbe1fed91e8706938f6e69642d9a4211967d89d20 (patch)
tree39d4706eb009c9ca0b32e38753cd3af40d17290a /2019
parentSolve day 3 part 1 (diff)
downloadaoc-be1fed91e8706938f6e69642d9a4211967d89d20.tar.gz
aoc-be1fed91e8706938f6e69642d9a4211967d89d20.zip
Solve day 3 part 2
Dang, I got screwed up by normalizing the lines in place rather than
just for the intersection function. When it came to calculating the
length of the final segment to the intersection, the "last" point was
sometimes the wrong end.
Diffstat (limited to '2019')
-rw-r--r--2019/day03.c43
1 files changed, 33 insertions, 10 deletions
diff --git a/2019/day03.c b/2019/day03.c
index 5d45bc0..6336ff7 100644
--- a/2019/day03.c
+++ b/2019/day03.c
@@ -10,14 +10,6 @@ struct Line {
 	struct Point a, b;
 };
 
-static void normalize(struct Line *l) {
-	if (l->a.x > l->b.x || l->a.y > l->b.y) {
-		struct Point p = l->a;
-		l->a = l->b;
-		l->b = p;
-	}
-}
-
 static size_t parse(struct Line *lines) {
 	char dir;
 	int dist;
@@ -33,13 +25,22 @@ static size_t parse(struct Line *lines) {
 			break; case 'R': point.x += dist;
 			break; default: abort();
 		}
-		lines[len].b = point;
-		normalize(&lines[len++]);
+		lines[len++].b = point;
 	}
 	return len;
 }
 
+static void normalize(struct Line *l) {
+	if (l->a.x > l->b.x || l->a.y > l->b.y) {
+		struct Point p = l->a;
+		l->a = l->b;
+		l->b = p;
+	}
+}
+
 static int intersect(struct Point *p, struct Line v, struct Line h) {
+	normalize(&v);
+	normalize(&h);
 	if (v.a.x != v.b.x) {
 		struct Line l = v;
 		v = h;
@@ -56,6 +57,10 @@ static int intersect(struct Point *p, struct Line v, struct Line h) {
 	return 1;
 }
 
+static int length(struct Line l) {
+	return abs(l.b.x - l.a.x) + abs(l.b.y - l.a.y);
+}
+
 int main(void) {
 	struct Line aLines[512];
 	struct Line bLines[512];
@@ -73,4 +78,22 @@ int main(void) {
 		}
 	}
 	printf("%d\n", min);
+
+	min = INT_MAX;
+	int aSteps = 0;
+	for (size_t a = 0; a < aLen; ++a) {
+		int bSteps = 0;
+		for (size_t b = 0; b < bLen; ++b) {
+			struct Point p;
+			if (intersect(&p, aLines[a], bLines[b]) && !(!p.x && !p.y)) {
+				int steps = aSteps + bSteps;
+				steps += length((struct Line) { aLines[a].a, p });
+				steps += length((struct Line) { bLines[b].a, p });
+				if (steps < min) min = steps;
+			}
+			bSteps += length(bLines[b]);
+		}
+		aSteps += length(aLines[a]);
+	}
+	printf("%d\n", min);
 }