-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmain1.go
168 lines (138 loc) · 2.04 KB
/
main1.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
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
package main
import (
"bufio"
"fmt"
"math"
"os"
"strconv"
"strings"
)
const (
cpy uint8 = iota
inc
dec
jnz
tgl
out
)
type Cmd struct {
Op uint8
X, Y string
}
var (
reg [4]int
cmds []Cmd
cursor int
)
func (c Cmd) Run(lastValue, countAlternate *int) {
switch c.Op {
case cpy:
x := getVal(c.X)
if r, ok := isReg(c.Y); ok {
reg[r] = x
}
case inc:
if r, ok := isReg(c.X); ok {
reg[r]++
}
case dec:
if r, ok := isReg(c.X); ok {
reg[r]--
}
case jnz:
x := getVal(c.X)
if x != 0 {
n := getVal(c.Y)
cursor += n - 1
}
case tgl:
x := getVal(c.X)
target := cursor + x
if target <= 0 || target >= len(cmds) {
return
}
cmd := cmds[target]
switch cmd.Op {
case cpy:
cmd.Op = jnz
case inc:
cmd.Op = dec
case dec:
cmd.Op = inc
case jnz:
cmd.Op = cpy
case tgl:
cmd.Op = inc
}
cmds[target] = cmd
case out:
x := getVal(c.X)
if *lastValue == x {
// exit
cursor = math.MaxInt64 - 1
}
*countAlternate++
*lastValue = x
}
}
func parse() {
scanner := bufio.NewScanner(os.Stdin)
for scanner.Scan() {
line := scanner.Text()
ff := strings.Fields(line)
var cmd = Cmd{
X: ff[1],
}
switch ff[0] {
case "cpy":
cmd.Op = cpy
case "inc":
cmd.Op = inc
case "dec":
cmd.Op = dec
case "jnz":
cmd.Op = jnz
case "tgl":
cmd.Op = tgl
case "out":
cmd.Op = out
}
if ff[0] == "cpy" || ff[0] == "jnz" {
cmd.Y = ff[2]
}
cmds = append(cmds, cmd)
}
}
func getVal(x string) int {
switch x {
case "a", "b", "c", "d":
r := []byte(x)[0]
return reg[r-'a']
default:
n, _ := strconv.Atoi(x)
return n
}
}
func isReg(s string) (int, bool) {
switch s {
case "a", "b", "c", "d":
r := []byte(s)
return int(r[0] - 'a'), true
}
return 0, false
}
func main() {
parse()
for i := 0; ; i++ {
reg[0] = i
var lastValue = -1
var countAlternate = 0
for cursor = 0; cursor < len(cmds); cursor++ {
cmds[cursor].Run(&lastValue, &countAlternate)
if countAlternate == 100 {
fmt.Println(i)
return
}
}
}
}