From 3399d661d5798041dfec7a06eab7ae5aad4ffc6c Mon Sep 17 00:00:00 2001
From: Nguyễn Gia Phong <cnx@loang.net>
Date: Thu, 5 Dec 2024 15:36:38 +0900
Subject: [aoc/2024] Finish day 5

---
 aoc/2024/05/part-one.c | 27 +++++++++++++++++++++++++++
 aoc/2024/05/part-two.c | 35 +++++++++++++++++++++++++++++++++++
 2 files changed, 62 insertions(+)
 create mode 100644 aoc/2024/05/part-one.c
 create mode 100644 aoc/2024/05/part-two.c

(limited to 'aoc/2024')

diff --git a/aoc/2024/05/part-one.c b/aoc/2024/05/part-one.c
new file mode 100644
index 0000000..4d2b560
--- /dev/null
+++ b/aoc/2024/05/part-one.c
@@ -0,0 +1,27 @@
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+int main()
+{
+	bool after[100][100] = {false};
+	unsigned char x, y;
+	while (scanf("%hhu|%hhu\n", &x, &y) == 2)
+		after[y][x] = true;
+
+	unsigned char line[90];
+	unsigned sum = y = 0;
+	do {
+		bool right = true;
+		do {
+			line[y] = x;
+			for (unsigned char i = 0; right && i < y; ++i)
+				if (after[line[i]][line[y]])
+					right = false;
+		} while (scanf(",%hhu", &x) == 1 && ++y);
+		if (right)
+			sum += line[y + 1 >> 1];
+	} while (y = 0, scanf("%hhu", &x) == 1);
+	printf("%u\n", sum);
+	return 0;
+}
diff --git a/aoc/2024/05/part-two.c b/aoc/2024/05/part-two.c
new file mode 100644
index 0000000..443e8b0
--- /dev/null
+++ b/aoc/2024/05/part-two.c
@@ -0,0 +1,35 @@
+#include <stdbool.h>
+#include <stdio.h>
+#include <stdlib.h>
+
+static bool after[100][100];
+
+int compare(const void *x, const void *y)
+{
+	return after[*(const unsigned char *) x][*(const unsigned char *) y];
+}
+
+int main()
+{
+	unsigned char x, y;
+	while (scanf("%hhu|%hhu\n", &x, &y) == 2)
+		after[y][x] = true;
+
+	unsigned char line[90];
+	unsigned sum = y = 0;
+	do {
+		bool right = true;
+		do {
+			line[y] = x;
+			for (unsigned char i = 0; right && i < y; ++i)
+				if (after[line[i]][line[y]])
+					right = false;
+		} while (scanf(",%hhu", &x) == 1 && ++y);
+		if (right)
+			continue;
+		qsort(line, ++y, 1, compare);
+		sum += line[y >> 1];
+	} while (y = 0, scanf("%hhu", &x) == 1);
+	printf("%u\n", sum);
+	return 0;
+}
-- 
cgit 1.4.1