Files
advent-of-code/2024/day-5/solution-1.sh
2024-12-05 20:46:22 +08:00

34 lines
787 B
Bash

#!/usr/bin/env bash
while read -r LINE
do
GREP_EXPR=$( printf "%s" "$LINE" | tr ',' '|' )
PASS_RULES=0
# Loop through rules and find a breaking rule
while read -r RULE
do
GREPC=$( printf "%s" "$LINE" | grep -c "$RULE" )
if [[ $GREPC -ne 1 ]]
then
#printf "%s rule violated for %s \n" "$RULE" "$LINE"
PASS_RULES=1
break
fi
# Filter rules that only has included pages
done <<< "$( < input-rules grep -E "($GREP_EXPR)\\|($GREP_EXPR)" | sed 's/|/,.*/')"
# All rules have passed
[[ $PASS_RULES -eq 0 ]] && printf "%s\n" "$LINE"
done < input-updates |
tr ',' ' ' |
awk '
BEGIN{ total = 0 }
{
if (NF % 2 == 1) {
idx = int( NF / 2 ) + 1
} else {
idx = NF / 2
}
total += $idx
}
END{ print total }'