-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
88 lines (78 loc) · 1.55 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
package main
import (
"io"
"regexp"
aoc "github.com/teivah/advent-of-code"
)
var (
re = regexp.MustCompile(`mul\((\d{1,3}),(\d{1,3})\)`)
)
func fs1(input io.Reader) int {
lines := aoc.ReaderToStrings(input)
res := 0
for _, line := range lines {
matches := re.FindAllStringSubmatch(line, -1)
for _, match := range matches {
res += aoc.StringToInt(match[1]) * aoc.StringToInt(match[2])
}
}
return res
}
func fs2(input io.Reader) int {
lines := aoc.ReaderToStrings(input)
pq := aoc.NewPriorityQueue[elem](func(a, b elem) bool {
return a.position < b.position
})
res := 0
curDo := true
for _, line := range lines {
for _, v := range aoc.FindStringIndices(line, "do()") {
pq.Push(elem{
position: v,
do: true,
})
}
for _, v := range aoc.FindStringIndices(line, "don't()") {
pq.Push(elem{
position: v,
dont: true,
})
}
for _, match := range aoc.RegexpFindSubmatches(line, re) {
m := mul{
x: aoc.StringToInt(line[match.CapturingGroups[0].Start:match.CapturingGroups[0].End]),
y: aoc.StringToInt(line[match.CapturingGroups[1].Start:match.CapturingGroups[1].End]),
}
pq.Push(elem{
position: match.Start,
mul: true,
vmul: m,
})
}
for !pq.IsEmpty() {
e := pq.Pop()
switch {
case e.do:
curDo = true
case e.dont:
curDo = false
case e.mul:
if curDo {
res += e.vmul.x * e.vmul.y
}
}
}
}
return res
}
type elem struct {
position int
do bool
dont bool
mul bool
vmul mul
}
type mul struct {
x int
y int
}