2020 Day 8 Complete!
This commit is contained in:
60
2020/day08/main.go
Normal file
60
2020/day08/main.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
|
||||
h "git.bullercodeworks.com/brian/adventofcode/helpers"
|
||||
)
|
||||
|
||||
func main() {
|
||||
fmt.Println("# Day 7")
|
||||
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")
|
||||
}
|
||||
Reference in New Issue
Block a user