From cff6d376950a5c3fd09dd0888ef0d4ab20f4b51a Mon Sep 17 00:00:00 2001 From: June McEnroe Date: Tue, 3 Dec 2019 01:03:42 -0500 Subject: Solve day 3 part 1 --- 2019/day03.c | 76 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 76 insertions(+) create mode 100644 2019/day03.c (limited to '2019') diff --git a/2019/day03.c b/2019/day03.c new file mode 100644 index 0000000..5d45bc0 --- /dev/null +++ b/2019/day03.c @@ -0,0 +1,76 @@ +#include +#include +#include + +struct Point { + int x, y; +}; + +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; + size_t len = 0; + struct Point point = { 0, 0 }; + while (EOF != scanf("%c%d,", &dir, &dist)) { + if (dir == '\n') break; + lines[len].a = point; + switch (dir) { + break; case 'U': point.y += dist; + break; case 'D': point.y -= dist; + break; case 'L': point.x -= dist; + break; case 'R': point.x += dist; + break; default: abort(); + } + lines[len].b = point; + normalize(&lines[len++]); + } + return len; +} + +static int intersect(struct Point *p, struct Line v, struct Line h) { + if (v.a.x != v.b.x) { + struct Line l = v; + v = h; + h = l; + } + if (v.a.y == v.b.y) return 0; + if (h.a.x == h.b.x) return 0; + if (h.a.y < v.a.y) return 0; + if (h.a.y > v.b.y) return 0; + if (h.a.x > v.a.x) return 0; + if (h.b.x < v.a.x) return 0; + p->x = v.a.x; + p->y = h.a.y; + return 1; +} + +int main(void) { + struct Line aLines[512]; + struct Line bLines[512]; + size_t aLen = parse(aLines); + size_t bLen = parse(bLines); + + int min = INT_MAX; + for (size_t a = 0; a < aLen; ++a) { + for (size_t b = 0; b < bLen; ++b) { + struct Point p; + if (!intersect(&p, aLines[a], bLines[b])) continue; + if (!p.x && !p.y) continue; + int dist = abs(p.x) + abs(p.y); + if (dist < min) min = dist; + } + } + printf("%d\n", min); +} -- cgit 1.4.1