summary refs log tree commit diff homepage
path: root/2019/day03.c
blob: 6336ff719bc0888e3844c2f4962e9b64cb50ef8a (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
#include <limits.h>
#include <stdio.h>
#include <stdlib.h>

struct Point {
	int x, y;
};

struct Line {
	struct Point a, b;
};

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;
	}
	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;
		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;
}

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];
	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);

	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);
}