summaryrefslogtreecommitdiff
path: root/3a.c
diff options
context:
space:
mode:
authorAdam Spragg <adam@spra.gg>2022-12-04 16:47:21 +0000
committerAdam Spragg <adam@spra.gg>2022-12-04 16:47:21 +0000
commite0c2037ee5cede636e907e8af462371ee0e775db (patch)
treea2546a2e5cafe43ef67737d774e7ad0fd8d1d781 /3a.c
Advent of code 2022 problems 1-4
Diffstat (limited to '3a.c')
-rw-r--r--3a.c65
1 files changed, 65 insertions, 0 deletions
diff --git a/3a.c b/3a.c
new file mode 100644
index 0000000..676db86
--- /dev/null
+++ b/3a.c
@@ -0,0 +1,65 @@
+
+#include <stdio.h>
+#include <stdlib.h>
+#include <string.h>
+
+
+int
+chrcmp(void const * a, void const * b)
+{
+ return (*(char const *) a) - *((char const *) b);
+}
+
+
+int
+priority(int c)
+{
+ if (c >= 'A' && c <= 'Z')
+ return 27 + c - 'A';
+ if (c >= 'a' && c <= 'z')
+ return 1 + c - 'a';
+ fprintf(stderr, "Unexpected priority request: %c\n", c);
+ return -1;
+}
+
+
+int
+main()
+{
+ char buf[BUFSIZ];
+ int score = 0;
+
+ while (fgets(buf, sizeof(buf), stdin)) {
+ int len, i, j;
+
+ len = strlen(buf);
+ if (len && buf[len - 1] == '\n')
+ --len;
+ if (len % 2 == 1)
+ fprintf(stderr, "Unexpected length: %d\n", len);
+
+ qsort(buf, len / 2, 1, chrcmp);
+ qsort(buf + len / 2, len / 2, 1, chrcmp);
+
+ i = 0;
+ j = len / 2;
+ while (i < len / 2 && j < len) {
+ if (buf[i] < buf[j])
+ ++i;
+ else if (buf[j] < buf[i])
+ ++j;
+ else
+ break;
+ }
+ if (i >= len / 2 || j >= len) {
+ fprintf(stderr, "No match found in %s\n", buf);
+ return -1;
+ }
+ score += priority(buf[i]);
+ }
+
+ printf("Score: %d\n", score);
+
+ return 0;
+}
+