From b66b2d098e975a301926ee9deab8f9e51d9ce789 Mon Sep 17 00:00:00 2001 From: Clement Date: Thu, 5 Dec 2024 20:46:22 +0800 Subject: [PATCH] Working part 2 solution --- 2024/day-5/solution-1.sh | 5 +--- 2024/day-5/solution-2.sh | 58 ++++++++++++++++++++++++++++++++++++++++ 2 files changed, 59 insertions(+), 4 deletions(-) create mode 100644 2024/day-5/solution-2.sh diff --git a/2024/day-5/solution-1.sh b/2024/day-5/solution-1.sh index 8ffb5f0..e94ee4d 100644 --- a/2024/day-5/solution-1.sh +++ b/2024/day-5/solution-1.sh @@ -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 ' diff --git a/2024/day-5/solution-2.sh b/2024/day-5/solution-2.sh new file mode 100644 index 0000000..a62fa22 --- /dev/null +++ b/2024/day-5/solution-2.sh @@ -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 }'