Implemented caching system

This commit is contained in:
2024-12-11 17:32:45 +08:00
parent d9a1e9fce3
commit d2d4bf7a64

View File

@ -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
# 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<DEPTH; i++ ))
do
blink_rocks
ROCKS_TO_BLINK=( "${BLINKED_ROCKS[@]}" )
read -r -a ROCKS_TO_BLINK <<< "$( printf "%s " "${BLINKED_ROCKS[@]}" )"
done
FINAL_LIST+=( "${BLINKED_ROCKS[@]}" )
KV_CACHE[$ROCK]=$( printf "%s " "${BLINKED_ROCKS[@]}" )
INTER_LIST_1+=( "${BLINKED_ROCKS[@]}" )
fi
done
printf "%s " "${FINAL_LIST[@]}"
printf "\n"
read -r -a FINAL_LIST <<< "$( printf "%s " "${INTER_LIST_1[@]}" )"
# All rocks are calculated $DEPTH ahead
(( POSITION+=DEPTH ))
done
#FINAL_LIST+=( "${BLINKED_ROCKS[@]}" )
# Dump KV cache for debugging
if [[ $DUMP_KV_CACHE -eq 0 ]]
then
printf "Number of keys in KV cache: %s\n" "${#KV_CACHE[@]}"
printf "Dumping KV CACHE\n"
for KEY in "${!KV_CACHE[@]}"
do
printf "Key: %s, Value: %s\n" "$KEY" "${KV_CACHE[$KEY]}"
done | sort
fi
#printf "%s " "${FINAL_LIST[@]}"
#printf "\n"
printf "%s\n" "${#FINAL_LIST[@]}"