-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
139 lines (128 loc) · 2.41 KB
/
main.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
package main
import (
_ "embed"
"fmt"
"log"
"os"
"regexp"
"strconv"
"strings"
aoc "github.com/beanz/advent/lib-go"
)
//go:embed input.txt
var input []byte
type Inst struct {
kind string
args []string
}
func (i *Inst) String() string {
return fmt.Sprintf("%s %v", i.kind, i.args)
}
type Game struct {
inst []*Inst
ip int
reg map[string]int
debug bool
}
func (g *Game) String() string {
s := ""
for _, r := range []string{"a", "b", "c", "d"} {
s += fmt.Sprintf("%d ", g.reg[r])
}
s += fmt.Sprintf("%d: %s", g.ip, g.inst[g.ip])
return s
}
func readGame(input string) *Game {
lines := strings.Split(input, "\n")
g := &Game{[]*Inst{}, 0, map[string]int{}, false}
g.reg["a"] = 0
g.reg["b"] = 0
g.reg["c"] = 0
g.reg["d"] = 0
instRe := regexp.MustCompile(`^(inc|dec|jnz|cpy|out)\s+(.*)$`)
for _, l := range lines[:len(lines)-1] {
m := instRe.FindStringSubmatch(l)
if m == nil {
log.Fatalf("Invalid instruction: %s\n", l)
}
g.inst = append(g.inst, &Inst{m[1], strings.Split(m[2], " ")})
}
return g
}
func (g *Game) RegValueOrImmediate(s string) int {
if s == "a" || s == "b" || s == "c" || s == "d" {
return g.reg[s]
}
val, _ := strconv.Atoi(s)
return val
}
func (g *Game) Run() bool {
g.ip = 0
out := 0
outCount := 0
for g.ip < len(g.inst) {
if g.debug {
fmt.Printf("%s\n", g)
}
in := g.inst[g.ip]
switch in.kind {
case "inc":
g.reg[in.args[0]]++
g.ip++
case "dec":
g.reg[in.args[0]]--
g.ip++
case "cpy":
g.reg[in.args[1]] = g.RegValueOrImmediate(in.args[0])
g.ip++
case "jnz":
val := g.RegValueOrImmediate(in.args[0])
jmp := g.RegValueOrImmediate(in.args[1])
if val == 0 {
jmp = 1
}
g.ip += jmp
case "out":
val := g.RegValueOrImmediate(in.args[0])
if val != out {
if g.debug {
fmt.Printf("out called but with %d not %d\n", val, out)
}
return false
}
if g.debug {
fmt.Printf("out called with %d\n", val)
}
if outCount > 20 {
return true
}
out = 1 - out
outCount++
g.ip++
default:
fmt.Fprintf(os.Stderr, "Unsupported instruction: %s\n", in)
g.ip++
}
}
return false
}
func (g *Game) Part1() int {
for a := 0; ; a++ {
if g.debug {
fmt.Printf("Testing %d\n", a)
}
g.reg["a"] = a
if g.Run() {
return a
}
}
return -1
}
func main() {
game := readGame(aoc.InputString(input))
p1 := game.Part1()
if !benchmark {
fmt.Printf("Part 1: %d\n", p1)
}
}
var benchmark = false