]> git.sommitrealweird.co.uk Git - advent-of-code-2019.git/blob - day2/computer.sh
Day 3 2019
[advent-of-code-2019.git] / day2 / computer.sh
1 #!/bin/bash
2
3 exec 3<input.txt
4
5 OLDIFS=$IFS
6 IFS="," read -u 3 -a orig_data
7 IFS=$OLDIFS
8
9 run_program() {
10     noun=$1
11     verb=$2
12     data=("${orig_data[@]}")
13     data[1]=$noun
14     data[2]=$verb
15     pos=0
16     while [ $pos -le ${#data[@]} ]; do
17         loc1=${data[$((pos+1))]}
18         loc2=${data[$((pos+2))]}
19         res_loc=${data[$((pos+3))]}
20         case ${data[$pos]} in
21             1)
22                 data[$res_loc]=$((${data[$loc1]}+${data[$loc2]}))
23                 ;;
24             2)
25                 data[$res_loc]=$((${data[$loc1]}*${data[$loc2]}))
26                 ;;
27             99)
28                 break
29                 ;;
30             *)
31                 echo "Invalid opcode: ${data[$pos]} at position $pos"
32                 exit 1
33         esac
34         pos=$((pos+4))
35     done
36
37     echo "${data[0]}"
38 }
39
40 echo "Part 1: $(run_program 12 2)"
41
42 desired_output=19690720
43
44 for (( noun=0; noun < 100; noun++)); do
45     for (( verb=0; verb < 100; verb++)); do
46         if [ $(run_program $noun $verb) -eq $desired_output ]; then
47             echo "Part 2: $((noun * 100 + $verb)) $noun, $verb"
48             exit 0
49         fi
50     done
51 done