added part 2, not happy with it
This commit is contained in:
parent
ee64977754
commit
aca7a1211a
54
day8/main.go
54
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
|
||||
}
|
||||
}
|
||||
}
|
||||
|
|
Loading…
Reference in New Issue