Rename days to 2 digits always
[advent-of-code-2019.git] / day02 / computer.sh
diff --git a/day02/computer.sh b/day02/computer.sh
new file mode 100644 (file)
index 0000000..d240dc6
--- /dev/null
@@ -0,0 +1,51 @@
+#!/bin/bash
+
+exec 3<input.txt
+
+OLDIFS=$IFS
+IFS="," read -u 3 -a orig_data
+IFS=$OLDIFS
+
+run_program() {
+    noun=$1
+    verb=$2
+    data=("${orig_data[@]}")
+    data[1]=$noun
+    data[2]=$verb
+    pos=0
+    while [ $pos -le ${#data[@]} ]; do
+        loc1=${data[$((pos+1))]}
+        loc2=${data[$((pos+2))]}
+        res_loc=${data[$((pos+3))]}
+        case ${data[$pos]} in
+            1)
+                data[$res_loc]=$((${data[$loc1]}+${data[$loc2]}))
+                ;;
+            2)
+                data[$res_loc]=$((${data[$loc1]}*${data[$loc2]}))
+                ;;
+            99)
+                break
+                ;;
+            *)
+                echo "Invalid opcode: ${data[$pos]} at position $pos"
+                exit 1
+        esac
+        pos=$((pos+4))
+    done
+
+    echo "${data[0]}"
+}
+
+echo "Part 1: $(run_program 12 2)"
+
+desired_output=19690720
+
+for (( noun=0; noun < 100; noun++)); do
+    for (( verb=0; verb < 100; verb++)); do
+        if [ $(run_program $noun $verb) -eq $desired_output ]; then
+            echo "Part 2: $((noun * 100 + $verb)) $noun, $verb"
+            exit 0
+        fi
+    done
+done