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

68 lines
1.8 KiB
Bash
Raw Normal View History

2024-12-05 20:46:22 +08:00
#!/usr/bin/env bash
{
while read -r LINE
2024-12-05 20:46:22 +08:00
do
GREP_EXPR=$( printf "%s" "$LINE" | tr ',' '|' )
2024-12-05 23:31:27 +08:00
MATCH_COUNT=0
# Loop through rules and find a breaking rule
2024-12-05 20:46:22 +08:00
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"
2024-12-05 23:31:27 +08:00
MATCH_COUNT=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
2024-12-05 23:31:27 +08:00
[[ $MATCH_COUNT -eq 0 ]] && continue
printf "%s\n" "$LINE"
done < input-updates
} | {
while read -r LINE # Generate a hashmap and rebuild the entire line from rules
do
CACHED_LINE=$( printf "%s" "$LINE" | tr ',' '\n' )
while [[ $( printf "%s" "$CACHED_LINE" | wc -c ) -gt 0 ]]
2024-12-05 20:46:22 +08:00
do
# Loop through rules and build all the KVs
DAG_GREP_EXPR=$( printf "%s" "$CACHED_LINE" | paste -s -d '|' )
KV_ARRAY=( $( < input-rules grep -E "($DAG_GREP_EXPR)\\|($DAG_GREP_EXPR)" | tr '|' ' ' | paste -s -d ' ') )
# Going through dependencies to find final key
KEY=${KV_ARRAY[0]}
while true
do
BREAK=0
for (( i=0; i<${#KV_ARRAY[@]}; i+=2 )) # Check if key exists
do
if [[ ${KV_ARRAY[$i]} -eq $KEY ]]
then
KEY=${KV_ARRAY[$i+1]}
BREAK=1
break
fi
done
if [[ $BREAK -eq 1 ]] ; then continue ; else break ; fi
done
printf "%s\n" "$KEY"
CACHED_LINE=$( printf "%s" "$CACHED_LINE" | grep -v "$KEY" )
done | tac | paste -s -d' '
done
} |
2024-12-05 20:46:22 +08:00
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 }'