2016-day12: assembly computer

This commit is contained in:
alexchao26
2020-12-23 20:17:42 -05:00
parent afa0f4384d
commit 0c00fc6cba
2 changed files with 89 additions and 0 deletions
+63
View File
@@ -0,0 +1,63 @@
package main
import (
"flag"
"fmt"
"strconv"
"strings"
"github.com/alexchao26/advent-of-code-go/cast"
"github.com/alexchao26/advent-of-code-go/util"
)
func main() {
var part int
flag.IntVar(&part, "part", 1, "part 1 or 2")
flag.Parse()
fmt.Println("Running part", part)
ans := assemblyComputer(util.ReadFile("./input.txt"), part)
fmt.Println("Output:", ans)
}
func assemblyComputer(input string, part int) int {
instructions := strings.Split(input, "\n")
registers := map[string]int{} // a b c d = 0
var instIndex int
if part == 2 {
registers["c"] = 1
}
for instIndex < len(instructions) {
parts := strings.Split(instructions[instIndex], " ")
switch parts[0] {
case "cpy":
valX, err := strconv.Atoi(parts[1])
if err != nil {
valX = registers[parts[1]]
}
registers[parts[2]] = valX
instIndex++
case "inc":
registers[parts[1]]++
instIndex++
case "dec":
registers[parts[1]]--
instIndex++
case "jnz":
valX, err := strconv.Atoi(parts[1])
if err != nil {
valX = registers[parts[1]]
}
if valX != 0 {
instIndex += cast.ToInt(parts[2])
} else {
instIndex++
}
}
}
return registers["a"]
}
+26
View File
@@ -0,0 +1,26 @@
package main
import (
"testing"
"github.com/alexchao26/advent-of-code-go/util"
)
func Test_assemblyComputer(t *testing.T) {
tests := []struct {
name string
input string
part int
want int
}{
{"actual_part1", util.ReadFile("input.txt"), 1, 318077},
{"actual_part2", util.ReadFile("input.txt"), 2, 9227731},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := assemblyComputer(tt.input, tt.part); got != tt.want {
t.Errorf("assemblyComputer() = %v, want %v", got, tt.want)
}
})
}
}