aboutsummaryrefslogtreecommitdiff
path: root/2024/05/puzzle-2.awk
blob: 6e60b668de41a11ad0d0a89b2183e115e1a6914d (plain) (blame)
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
#!/usr/bin/gawk -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 }