From 8528013fb10ae7aedb6a40f5ece5ee08eb42e9df Mon Sep 17 00:00:00 2001 From: Adam Spragg Date: Sun, 15 Jan 2023 10:36:48 +0000 Subject: Puzzle 4: Consolidate 4a/4b programs into `4` with `-p` option Like the later puzzles --- 4.c | 81 +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) create mode 100644 4.c (limited to '4.c') diff --git a/4.c b/4.c new file mode 100644 index 0000000..1f183b7 --- /dev/null +++ b/4.c @@ -0,0 +1,81 @@ + +#include +#include +#include + + +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; +} + -- cgit v1.2.1