Files
advent-of-code/2024/day-5/solution-2.sh

59 lines
1.6 KiB
Bash
Raw Normal View History

2024-12-05 20:46:22 +08:00
#!/usr/bin/env bash
rm key-*
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/|/,.*/')"
# Don't process for valid lines
[[ $PASS_RULES -eq 0 ]] && continue
# Generate a hashmap and rebuild the entire line from rules
CACHED_LINE=$LINE
while [[ $( printf "%s" "$CACHED_LINE" | tr ',' '\n' | wc -c ) -gt 0 ]]
do
# Loop through rules and build all the KVs
rm key-*
DAG_GREP_EXPR=$( printf "%s" "$CACHED_LINE" | tr ',' '|' )
while read -r RULE
do
KEY=$( printf "%s" "$RULE" | cut -f1 -d'|' )
VALUE=$( printf "%s" "$RULE" | cut -f2 -d'|' )
printf "%s" "$VALUE" > key-"$KEY"
done <<< "$( < input-rules grep -E "($DAG_GREP_EXPR)\\|($DAG_GREP_EXPR)" )"
KEY=$( printf "%s" "$CACHED_LINE" | tr ',' '\n' | head -1 )
# Going through dependencies to find final key
while [[ -f key-$KEY ]]
do
KEY=$( cat "key-$KEY" )
done
printf "%s\n" "$KEY"
CACHED_LINE=$( printf "%s" "$CACHED_LINE" | tr ',' '\n' | grep -v "$KEY" | paste -s -d ',' )
done | tac | paste -s -d' '
done < input-updates |
tee final-output |
awk '
BEGIN{ total = 0 }
{
if (NF % 2 == 1) {
idx = int( NF / 2 ) + 1
} else {
idx = NF / 2
}
total += $idx
}
END{ print total }'