From aca7a1211aebcbee59ced8dde325302375759f4b Mon Sep 17 00:00:00 2001 From: Nihilazo Date: Tue, 8 Dec 2020 15:59:27 +0000 Subject: [PATCH] added part 2, not happy with it --- day8/main.go | 54 +++++++++++++++++++++++++++++++++++----------------- 1 file changed, 37 insertions(+), 17 deletions(-) diff --git a/day8/main.go b/day8/main.go index 95f2ffe..250c2ff 100644 --- a/day8/main.go +++ b/day8/main.go @@ -7,6 +7,28 @@ import ( "strings" ) +func run(p program) (acc int, err error) { + ip := 0 // Instruction Pointer + a := 0 // Accumulator "register" + for ip < len(p) { // while we're still in the program + i := &p[ip] // instruction at pointer + i.Executions = i.Executions + 1 + if i.Executions == 2 { + return a, fmt.Errorf("Early exit input:%d", ip-1) + } + switch i.Op { + case "nop": + ip += 1 + case "jmp": + ip += i.Arg + case "acc": + a += i.Arg + ip += 1 + } + } + return a, nil +} + type instruction struct { Executions int // Execution count Arg int @@ -26,24 +48,22 @@ func main() { p = append(p, instruction{Arg: n, Op: f[0]}) } } - ip := 0 // Instruction Pointer - a := 0 // Accumulator "register" - for ip < len(p) { // while we're still in the program - i := &p[ip] // instruction at pointer - fmt.Println(i) - i.Executions = i.Executions + 1 - if i.Executions == 2 { - fmt.Println(a) - return + working := make(program, len(p)) + copy(working, p) + o, _ := run(working) + fmt.Println("Part 1: ", o) + for i, v := range p { + working := make(program, len(p)) + copy(working, p) + if v.Op == "nop" { + working[i].Op = "jmp" + } else if v.Op == "jmp" { + working[i].Op = "nop" } - switch i.Op { - case "nop": - ip += 1 - case "jmp": - ip += i.Arg - case "acc": - a += i.Arg - ip += 1 + a, err := run(working) + if err == nil { + fmt.Println("Part 2: ", a) + return } } }