diff --git a/2024/day-11/solution-2.sh b/2024/day-11/solution-2.sh index 1e2df16..84b92c5 100644 --- a/2024/day-11/solution-2.sh +++ b/2024/day-11/solution-2.sh @@ -1,7 +1,13 @@ #!/usr/bin/env bash +declare -A KV_CACHE read -r -a ROCK_LIST <<< "$( cat input )" -BLINK_NUM=25 +DUMP_KV_CACHE=0 +BLINK_NUM=75 +# KV Cache provides n depth search, +# but must always be fully divisible by BLINK_NUM +DEPTH=5 +if [[ $(( BLINK_NUM % DEPTH )) -gt 0 ]] ;then printf "BLINK_NUM DEPTH mismatch.\n" && exit ; fi ROCK_RETURN=() ROCK_NUM=0 @@ -10,7 +16,7 @@ blink_rock () { #printf "Blinking rock : %s\n" "$ROCK_NUM" >&2 # Remove leading zeroes - ROCK_NUM=$(( 10#$ROCK_NUM )) + #ROCK_NUM=$(( 10#$ROCK_NUM )) # Rule 1 : Convert 0 to 1 if [[ $ROCK_NUM -eq 0 ]] then @@ -23,7 +29,7 @@ blink_rock () { if [[ $(( DIGIT_COUNT % 2 )) -eq 0 ]] && [[ $DIGIT_COUNT -gt 0 ]] then HALF=$(( DIGIT_COUNT / 2 )) - read -r -a ROCK_RETURN <<< "$( printf "%s %s " "${ROCK_NUM:0:$HALF}" "${ROCK_NUM:$HALF}" )" + read -r -a ROCK_RETURN <<< "$( printf "%s %s " "$(( 10#${ROCK_NUM:0:$HALF} ))" "$(( 10#${ROCK_NUM:$HALF} ))" )" return fi @@ -49,18 +55,56 @@ blink_rocks () { #printf "\n" >&2 } -FINAL_LIST=() -for ROCK_NUM in "${ROCK_LIST[@]}" +#FINAL_LIST=() +# Keeps track of +read -r -a FINAL_LIST <<< "$( printf "%s " "${ROCK_LIST[@]}" )" +POSITION=0 +while [[ $POSITION -lt $BLINK_NUM ]] do - printf "Rock: %s\n" "$ROCK_NUM" - ROCKS_TO_BLINK=( "$ROCK_NUM" ) - for (( i=0 ; i< BLINK_NUM; i++ )) + printf "%s Working on position %s\n" "$( date )" "$POSITION" + INTER_LIST_1=() + # Essentially move $DEPTH steps at a time + for ROCK in "${FINAL_LIST[@]}" do - blink_rocks - ROCKS_TO_BLINK=( "${BLINKED_ROCKS[@]}" ) + # Check if this is already cached + if [[ -v KV_CACHE["$ROCK"] ]] + then + # Retrieve cached entry + read -r -a X <<< "${KV_CACHE[$ROCK]}" + INTER_LIST_1+=( "${X[@]}" ) + #printf "Cache hit. Key: %s, Value: " "$ROCK" + #printf "%s " "${KV_CACHE[$ROCK]}" + #printf "\n" + else + # Build cache entry + ROCKS_TO_BLINK=( "$ROCK" ) + for (( i=0; i