aboutsummaryrefslogtreecommitdiff
path: root/2024/05/puzzle-2.awk
diff options
context:
space:
mode:
authorThomas Voss <mail@thomasvoss.com> 2024-12-05 09:39:07 +0100
committerThomas Voss <mail@thomasvoss.com> 2024-12-05 09:39:07 +0100
commit4f8745c22e16c7923047f02c405f4a6bf0be1a5d (patch)
tree2a8aa7dd4d01535148bf494f8fb191b9c5a58778 /2024/05/puzzle-2.awk
parent74226de3f925ce8314f06fe7fdb05dd42c0f434b (diff)
Add 2024 day 5 solutions
Diffstat (limited to '2024/05/puzzle-2.awk')
-rwxr-xr-x2024/05/puzzle-2.awk34
1 files changed, 34 insertions, 0 deletions
diff --git a/2024/05/puzzle-2.awk b/2024/05/puzzle-2.awk
new file mode 100755
index 0000000..a76c96a
--- /dev/null
+++ b/2024/05/puzzle-2.awk
@@ -0,0 +1,34 @@
+#!/usr/bin/awk -f
+
+function sort_page_numbers(i1, v1, i2, v2)
+{
+ if (v1 in rules[v2])
+ return +1
+ if (v2 in rules[v1])
+ return -1
+ return 0
+}
+
+BEGIN { FS = "[|,]" }
+
+/\|/ { rules[$1][$2] = 1 }
+/,/ {
+ delete seen
+ badent = 0
+
+ for (i = 1; i <= NF; i++) {
+ for (j in seen) {
+ if (j in rules[$i])
+ badent = 1
+ }
+ seen[$i] = 1
+ }
+ if (!badent)
+ next
+
+ split($0, xs)
+ asort(xs, xs, "sort_page_numbers")
+ mid += xs[(NF + 1) / 2]
+}
+
+END { print mid } \ No newline at end of file