summaryrefslogtreecommitdiff
path: root/4.c
blob: 1f183b767c1f871288ff1bfbcef5e2bf49390f01 (plain)
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
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>


char *
getsect(int * dest, char * pch, char expect)
{
	char * end;

	if (!pch)
		return NULL;
	*dest = strtol(pch, &end, 10);
	if (*dest == 0 && end == pch)
		return NULL;
	if (*end != expect)
		return NULL;
	if (expect)
		++end;
	return end;
}


int
main(int argc, char ** argv)
{
	char buf[BUFSIZ];
	int part = 1, i, overlaps = 0;

	while ((i = getopt(argc, argv, "p:")) != -1) {
		switch (i) {
		case 'p':
			part = atoi(optarg);
			break;

		default:
			return -1;
		}
	}

	while (fgets(buf, sizeof(buf), stdin)) {
		int n[4];
		char * pbuf;

		pbuf = getsect(&n[0], buf, '-');
		pbuf = getsect(&n[1], pbuf, ',');
		pbuf = getsect(&n[2], pbuf, '-');
		pbuf = getsect(&n[3], pbuf, '\n');
		if (!pbuf) {
			fprintf(stderr, "Unexpected line: %s\n", buf);
			return -1;
		}
		switch (part) {
		case 1:
			if ((n[2] >= n[0] && n[3] <= n[1])
					|| (n[0] >= n[2] && n[1] <= n[3]))
			{
				++overlaps;
			}
			break;

		case 2:
			if (!(n[3] < n[0] || n[2] > n[1])) {
				++overlaps;
			}
			break;

		default:
			fprintf(stderr, "Unexpected puzzle part %d\n", part);
			return -1;
		}
	}

	printf("%s overlaps: %d\n",
			part == 1 ? "Full" : "Partial",
			overlaps);

	return 0;
}