-
Notifications
You must be signed in to change notification settings - Fork 10
/
day03.go
69 lines (61 loc) · 1.43 KB
/
day03.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
package main
import (
"flag"
"fmt"
"io/ioutil"
"regexp"
"strconv"
"strings"
)
var inputFile = flag.String("inputFile", "inputs/day03.input", "Relative file path to use as input.")
type row []int
var pattern = regexp.MustCompile(`mul\(([0-9]+),([0-9]+)\)`)
var enable = regexp.MustCompile(`do\(\)`)
var disable = regexp.MustCompile(`don't\(\)`)
type valid struct {
pos, val int
}
func main() {
flag.Parse()
bytes, err := ioutil.ReadFile(*inputFile)
if err != nil {
return
}
contents := string(bytes)
split := strings.Split(contents, "\n")
fmt.Println(process(split[:len(split)-1], false))
fmt.Println(process(split[:len(split)-1], true))
}
func process(lines []string, obeyDont bool) int {
sum := 0
enabled := true
for _, s := range lines {
enables := enable.FindAllStringIndex(s, -1)
disables := disable.FindAllStringIndex(s, -1)
results := pattern.FindAllStringSubmatchIndex(s, -1)
var ops []valid
for _, r := range results {
a, _ := strconv.Atoi(s[r[2]:r[3]])
b, _ := strconv.Atoi(s[r[4]:r[5]])
ops = append(ops, valid{r[0], a * b})
}
var eIdx, dIdx, oIdx int
for i := 0; i < len(s); i++ {
if eIdx < len(enables) && enables[eIdx][0] == i {
enabled = true
eIdx++
}
if obeyDont && dIdx < len(disables) && disables[dIdx][0] == i {
enabled = false
dIdx++
}
if oIdx < len(ops) && ops[oIdx].pos == i {
if enabled {
sum += ops[oIdx].val
}
oIdx++
}
}
}
return sum
}