From 11d744f1cd2c87d7dc01c504e368d4cecd99aa47 Mon Sep 17 00:00:00 2001 From: Brett Parker Date: Tue, 15 Dec 2020 16:30:20 +0000 Subject: [PATCH] Use a variable reference for where to store the result, stop putting all results in to a huge array and then reading the answer from that. Save a fair chunk of memory. --- day15/memory.sh | 29 +++++++++++++++-------------- 1 file changed, 15 insertions(+), 14 deletions(-) diff --git a/day15/memory.sh b/day15/memory.sh index 4f16b3b..a2d9547 100755 --- a/day15/memory.sh +++ b/day15/memory.sh @@ -12,10 +12,11 @@ read_file() { get_answer() { local number=$1 local count=$2 + local -n __fn_result=$3 if [ ${lastseen[$number]+a} ]; then - answers[$count]=$((count-${lastseen[$number]}-1)) + __fn_result=$((count-${lastseen[$number]})) else - answers[$count]=0 + __fn_result=0 fi } @@ -39,40 +40,40 @@ filename="${1:-p1_436.txt}" read_file "$filename" declare -A lastseen -declare -a answers current_answer=-1 last_answer=-1 count=0 +result= + for number in ${data[@]}; do count=$((count+1)) last_answer=$current_answer if [ $last_answer -ge 0 ]; then lastseen[$last_answer]=$((count-1)) fi - answers[$count]=$number current_answer=$number done while [ $count -lt 2020 ]; do - count=$((count+1)) - get_answer $current_answer $count last_answer=$current_answer + get_answer $current_answer $count result + count=$((count+1)) + current_answer=$result lastseen[$last_answer]=$((count-1)) - current_answer=${answers[$count]} - $debug_func "$count: ${answers[$count]}" + $debug_func "$count: $current_answer" done -echo "Part 1: ${answers[$count]}" +echo "Part 1: $current_answer" while [ $count -lt 30000000 ]; do - count=$((count+1)) - get_answer $current_answer $count last_answer=$current_answer + get_answer $current_answer $count result + count=$((count+1)) + current_answer=$result lastseen[$last_answer]=$((count-1)) - current_answer=${answers[$count]} - $debug_func "$count: ${answers[$count]}" + $debug_func "$count: $current_answer" done -echo "Part 2: ${answers[$count]}" +echo "Part 2: $current_answer" -- 2.39.5