#!/bin/bash

set -u

read_file() {
    filename="$1"
    local IFS=","
    exec 3<"$filename"
    read -u 3 -a data
}

get_answer() {
    local number=$1
    local count=$2
    local -n __fn_result=$3
    if [ ${lastseen[$number]+a} ]; then
        __fn_result=$((count-${lastseen[$number]}))
    else
        __fn_result=0
    fi
}

do_nothing() {
    return
}

error_echo() {
    echo "$@" >&2
}

DEBUG="${DEBUG:-}"
debug_func=do_nothing

if [ -n "$DEBUG" ]; then
    debug_func="error_echo"
fi

filename="${1:-p1_436.txt}"

read_file "$filename"

declare -A lastseen

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
    current_answer=$number
done

while [ $count -lt 2020 ]; do
    last_answer=$current_answer
    get_answer $current_answer $count result
    count=$((count+1))
    current_answer=$result
    lastseen[$last_answer]=$((count-1))
    $debug_func "$count: $current_answer"
done

echo "Part 1: $current_answer"

while [ $count -lt 30000000 ]; do
    last_answer=$current_answer
    get_answer $current_answer $count result
    count=$((count+1))
    current_answer=$result
    lastseen[$last_answer]=$((count-1))
    $debug_func "$count: $current_answer"
done

echo "Part 2: $current_answer"
