diff --git a/2016/day12/main.go b/2016/day12/main.go new file mode 100644 index 0000000..38ede8d --- /dev/null +++ b/2016/day12/main.go @@ -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"] +} diff --git a/2016/day12/main_test.go b/2016/day12/main_test.go new file mode 100644 index 0000000..3e321bd --- /dev/null +++ b/2016/day12/main_test.go @@ -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) + } + }) + } +}