Working part 2 solution
This commit is contained in:
@ -17,10 +17,7 @@ do
|
|||||||
# Filter rules that only has included pages
|
# Filter rules that only has included pages
|
||||||
done <<< "$( < input-rules grep -E "($GREP_EXPR)\\|($GREP_EXPR)" | sed 's/|/,.*/')"
|
done <<< "$( < input-rules grep -E "($GREP_EXPR)\\|($GREP_EXPR)" | sed 's/|/,.*/')"
|
||||||
# All rules have passed
|
# All rules have passed
|
||||||
if [[ $PASS_RULES -eq 0 ]]
|
[[ $PASS_RULES -eq 0 ]] && printf "%s\n" "$LINE"
|
||||||
then
|
|
||||||
printf "%s\n" "$LINE"
|
|
||||||
fi
|
|
||||||
done < input-updates |
|
done < input-updates |
|
||||||
tr ',' ' ' |
|
tr ',' ' ' |
|
||||||
awk '
|
awk '
|
||||||
|
58
2024/day-5/solution-2.sh
Normal file
58
2024/day-5/solution-2.sh
Normal 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 }'
|
Reference in New Issue
Block a user