Skip to content

Instantly share code, notes, and snippets.

@rhowe
Created December 5, 2019 13:31
Show Gist options
  • Save rhowe/021b59b2873f03107a07ca3b67dc618e to your computer and use it in GitHub Desktop.
Save rhowe/021b59b2873f03107a07ca3b67dc618e to your computer and use it in GitHub Desktop.
AOC2019day5part2
#!/bin/bash
set -eu
IFS=, read -r -a ram < "$1"
getval() {
case $1 in
0) echo "${ram[$2]}" ;;
1) echo "$2" ;;
esac
}
jmpt() {
addrmode=$1
arg=$(getval "${addrmode:0:1}" "$2")
dest=$(getval "${addrmode:1:1}" "$3")
if [ "$arg" -ne 0 ]; then
pc=$dest
else
pc=$((pc+2))
fi
}
jmpf() {
addrmode=$1
arg=$(getval "${addrmode:0:1}" "$2")
dest=$(getval "${addrmode:1:1}" "$3")
if [ "$arg" -eq 0 ]; then
pc=$dest
else
pc=$((pc+2))
fi
}
add() {
addrmode=$1
src1=$(getval "${addrmode:0:1}" "$2")
src2=$(getval "${addrmode:1:1}" "$3")
dest=$4
ram[$dest]=$((src1 + src2))
pc=$((pc+3))
}
mul() {
addrmode=$1
src1=$(getval "${addrmode:0:1}" "$2")
src2=$(getval "${addrmode:1:1}" "$3")
dest=$4
ram[$dest]=$((src1 * src2))
pc=$((pc+3))
}
cmpl() {
addrmode=$1
src1=$(getval "${addrmode:0:1}" "$2")
src2=$(getval "${addrmode:1:1}" "$3")
dest=$4
if [ "$src1" -lt "$src2" ]; then
ans=1
else
ans=0
fi
ram[$dest]=$ans
pc=$((pc+3))
}
cmpe() {
addrmode=$1
src1=$(getval "${addrmode:0:1}" "$2")
src2=$(getval "${addrmode:1:1}" "$3")
dest=$4
if [ "$src1" -eq "$src2" ]; then
ans=1
else
ans=0
fi
ram[$dest]=$ans
pc=$((pc+3))
}
inb() {
addrmode=$1
dest=$2
input=5
ram[$dest]=$input
pc=$((pc+1))
}
outb() {
addrmode=$1
src=$(getval "${addrmode:0:1}" "$2")
echo $src
pc=$((pc+1))
}
pc=0
while true; do
opcode=$(printf %04d "${ram[$pc]}")
addrmode=$(rev <<<"${opcode%??}")
op=${opcode: -2}
pc=$((pc+1))
case $op in
01) add "$addrmode" "${ram[@]:$pc:3}" ;;
02) mul "$addrmode" "${ram[@]:$pc:3}" ;;
03) inb "$addrmode" "${ram[@]:$pc:1}" ;;
04) outb "$addrmode" "${ram[@]:$pc:1}" ;;
05) jmpt "$addrmode" "${ram[@]:$pc:2}" ;;
06) jmpf "$addrmode" "${ram[@]:$pc:2}" ;;
07) cmpl "$addrmode" "${ram[@]:$pc:3}" ;;
08) cmpe "$addrmode" "${ram[@]:$pc:3}" ;;
99) break ;;
*)
echo "Unknown opcode $opcode at $pc" >&2
exit 1
;;
esac
done
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment