Day 15 - p2 is brute force, there must be a nicer algorithm that I can't see
[advent-of-code-2020.git] / day15 / memory.sh
1 #!/bin/bash
2
3 set -u
4
5 read_file() {
6     filename="$1"
7     local IFS=","
8     exec 3<"$filename"
9     read -u 3 -a data
10 }
11
12 get_answer() {
13     local number=$1
14     local count=$2
15     if [ ${lastseen[$number]+a} ]; then
16         answers[$count]=$((count-${lastseen[$number]}-1))
17     else
18         answers[$count]=0
19     fi
20 }
21
22 do_nothing() {
23     return
24 }
25
26 error_echo() {
27     echo "$@" >&2
28 }
29
30 DEBUG="${DEBUG:-}"
31 debug_func=do_nothing
32
33 if [ -n "$DEBUG" ]; then
34     debug_func="error_echo"
35 fi
36
37 filename="${1:-p1_436.txt}"
38
39 read_file "$filename"
40
41 declare -A lastseen
42 declare -a answers
43
44 current_answer=-1
45 last_answer=-1
46 count=0
47
48 for number in ${data[@]}; do
49     count=$((count+1))
50     last_answer=$current_answer
51     if [ $last_answer -ge 0 ]; then
52         lastseen[$last_answer]=$((count-1))
53     fi
54     answers[$count]=$number
55     current_answer=$number
56 done
57
58 while [ $count -lt 2020 ]; do
59     count=$((count+1))
60     get_answer $current_answer $count
61     last_answer=$current_answer
62     lastseen[$last_answer]=$((count-1))
63     current_answer=${answers[$count]}
64     $debug_func "$count: ${answers[$count]}"
65 done
66
67 echo "Part 1: ${answers[$count]}"
68
69 while [ $count -lt 30000000 ]; do
70     count=$((count+1))
71     get_answer $current_answer $count
72     last_answer=$current_answer
73     lastseen[$last_answer]=$((count-1))
74     current_answer=${answers[$count]}
75     $debug_func "$count: ${answers[$count]}"
76 done
77
78 echo "Part 2: ${answers[$count]}"