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

66 lines
1.7 KiB
Bash
Raw Normal View History

2024-12-05 20:46:22 +08:00
#!/usr/bin/env bash
2024-12-06 12:46:43 +08:00
INPUT_RULES=$(sort -n input-rules)
{
while read -r LINE
2024-12-05 20:46:22 +08:00
do
GREP_EXPR=$( printf "%s" "$LINE" | tr ',' '|' )
2024-12-06 01:09:33 +08:00
BEEG_AWK_EXPR=$(
printf "%s" "$INPUT_RULES" |
grep -E "($GREP_EXPR)\\|($GREP_EXPR)" |
sed -E 's/(.*)\|(.*)/\1,.*\2/; s&^&/&; s&$&/&' |
paste -s -d '@' |
sed 's/@/ \&\& /g'
)
AWK_MATCH=$( printf "%s" "$LINE" | awk "$BEEG_AWK_EXPR" | wc -c )
# Don't process for valid lines
2024-12-06 01:09:33 +08:00
if [[ $AWK_MATCH -gt 0 ]] ; then continue; fi
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 '|' )
2024-12-06 01:32:07 +08:00
read -r -a 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]}
2024-12-06 02:46:03 +08:00
BREAK=1
break
fi
done
2024-12-06 12:46:43 +08:00
if [[ $BREAK -eq 0 ]] ; then 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
awk '
BEGIN{ total = 0 }
{
if (NF % 2 == 1) {
idx = int( NF / 2 ) + 1
} else {
idx = NF / 2
}
total += $idx
}
END{ print total }'