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"
|
"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 {
|
type instruction struct {
|
||||||
Executions int // Execution count
|
Executions int // Execution count
|
||||||
Arg int
|
Arg int
|
||||||
|
@ -26,24 +48,22 @@ func main() {
|
||||||
p = append(p, instruction{Arg: n, Op: f[0]})
|
p = append(p, instruction{Arg: n, Op: f[0]})
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
ip := 0 // Instruction Pointer
|
working := make(program, len(p))
|
||||||
a := 0 // Accumulator "register"
|
copy(working, p)
|
||||||
for ip < len(p) { // while we're still in the program
|
o, _ := run(working)
|
||||||
i := &p[ip] // instruction at pointer
|
fmt.Println("Part 1: ", o)
|
||||||
fmt.Println(i)
|
for i, v := range p {
|
||||||
i.Executions = i.Executions + 1
|
working := make(program, len(p))
|
||||||
if i.Executions == 2 {
|
copy(working, p)
|
||||||
fmt.Println(a)
|
if v.Op == "nop" {
|
||||||
return
|
working[i].Op = "jmp"
|
||||||
|
} else if v.Op == "jmp" {
|
||||||
|
working[i].Op = "nop"
|
||||||
}
|
}
|
||||||
switch i.Op {
|
a, err := run(working)
|
||||||
case "nop":
|
if err == nil {
|
||||||
ip += 1
|
fmt.Println("Part 2: ", a)
|
||||||
case "jmp":
|
return
|
||||||
ip += i.Arg
|
|
||||||
case "acc":
|
|
||||||
a += i.Arg
|
|
||||||
ip += 1
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue