Working part 2 solution

This commit is contained in:
2024-12-05 20:46:22 +08:00
parent 6a0ef4fea6
commit b66b2d098e
2 changed files with 59 additions and 4 deletions

View File

@ -17,10 +17,7 @@ do
# Filter rules that only has included pages
done <<< "$( < input-rules grep -E "($GREP_EXPR)\\|($GREP_EXPR)" | sed 's/|/,.*/')"
# All rules have passed
if [[ $PASS_RULES -eq 0 ]]
then
printf "%s\n" "$LINE"
fi
[[ $PASS_RULES -eq 0 ]] && printf "%s\n" "$LINE"
done < input-updates |
tr ',' ' ' |
awk '

58
2024/day-5/solution-2.sh Normal file
View File

@ -0,0 +1,58 @@
#!/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 }'