adventofcode/2020/day08/main.go

61 lines
1.1 KiB
Go
Raw Normal View History

2020-12-08 15:52:49 +00:00
package main
import (
"fmt"
"strings"
h "git.bullercodeworks.com/brian/adventofcode/helpers"
)
func main() {
2020-12-09 13:28:33 +00:00
fmt.Println("# Day 8")
2020-12-08 15:52:49 +00:00
inp := h.StdinToStringSlice()
FixProg(inp)
}
func RunProg(inp []string) {
var acc int
var ptr int
hist := make(map[int]int)
for ptr < len(inp) {
if _, ok := hist[ptr]; ok {
fmt.Printf("Instruction %d repeated. Acc: %d\n", ptr, acc)
return
}
hist[ptr] = acc
pts := strings.Split(inp[ptr], " ")
switch pts[0] {
case "acc":
acc = acc + h.Atoi(pts[1])
ptr++
case "jmp":
ptr = ptr + h.Atoi(pts[1])
case "nop":
ptr++
}
}
}
func FixProg(inp []string) {
p := NewProgram(inp)
chchch := p.CountOpCodes(NOP, JMP)
for ch := 1; ch <= chchch; ch++ {
np := p.Copy()
chOp := np.FindNthOp(ch, NOP, JMP)
if chOp >= 0 {
if np.Instructions[chOp].OpCode == NOP {
np.Instructions[chOp].OpCode = JMP
} else if np.Instructions[chOp].OpCode == JMP {
np.Instructions[chOp].OpCode = NOP
}
res := np.Run()
if res == 0 {
fmt.Println("Accumulator:", np.Accumulator)
return
}
}
fmt.Println("Changing", ch, "didn't fix it")
}
fmt.Println("Failed to fix program")
}