-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathmain.go
115 lines (101 loc) · 1.73 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
package main
import (
"bufio"
"io"
lib "github.com/teivah/advent-of-code"
)
func fs1(input io.Reader) int {
scanner := bufio.NewScanner(input)
var funcs []apply
for scanner.Scan() {
line := scanner.Text()
del := lib.NewDelimiter(line, " ")
switch del.GetString(0) {
case "nop":
funcs = append(funcs, nop())
case "acc":
funcs = append(funcs, acc(del.GetInt(1)))
case "jmp":
funcs = append(funcs, jmp(del.GetInt(1)))
default:
panic(line)
}
}
s := State{}
set := make(map[int]bool)
for {
set[s.offset] = true
acc := s.acc
funcs[s.offset](&s)
if set[s.offset] {
return acc
}
}
return -1
}
type State struct {
offset int
acc int
}
type apply func(s *State)
func acc(v int) apply {
return func(s *State) {
s.acc += v
s.offset++
}
}
func jmp(v int) apply {
return func(s *State) {
s.offset += v
}
}
func nop() apply {
return func(s *State) {
s.offset++
}
}
func fs2(input io.Reader) int {
lines := lib.ReaderToStrings(input)
last := -1
for {
var funcs []apply
modified := false
for i, line := range lines {
del := lib.NewDelimiter(line, " ")
switch del.GetString(0) {
case "nop":
funcs = append(funcs, nop())
case "acc":
funcs = append(funcs, acc(del.GetInt(1)))
case "jmp":
if i > last && !modified {
funcs = append(funcs, nop())
last = i
modified = true
} else {
funcs = append(funcs, jmp(del.GetInt(1)))
}
default:
panic(line)
}
}
s := State{}
set := make(map[int]bool)
terminated := true
for {
set[s.offset] = true
if s.offset >= len(funcs) {
break
}
funcs[s.offset](&s)
if set[s.offset] {
terminated = false
break
}
}
if terminated {
return s.acc
}
}
return -1
}