-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday03-1.go
92 lines (80 loc) · 1.96 KB
/
day03-1.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
package main
import (
"fmt"
"regexp"
"strconv"
)
// Extract numbers from a line.
var day3NumbersRe = regexp.MustCompile(`\d+`)
// day3Point represents a point in the schematic through indices.
type day3Point struct {
idxY, idxX int
}
// day3Number represents a number by its position in the schematic.
type day3Number struct {
day3Point
len int
}
func (d day3Number) value(lines []string) (int, error) {
str := lines[d.idxY][d.idxX : d.idxX+d.len]
return strconv.Atoi(str)
}
func day3part1(filename string) (string, error) {
lines, err := allLines(filename)
if err != nil {
return "", err
}
numsWithSymbols := make([]day3Number, 0)
for _, num := range day3AllNumbers(lines) {
day3WalkAroundNumber(num, lines, func(y, x int, b byte) bool {
if b != '.' {
numsWithSymbols = append(numsWithSymbols, num)
return false
}
return true
})
}
var total int
for _, num := range numsWithSymbols {
val, err := num.value(lines)
if err != nil {
return "", nil
}
total += val
}
return fmt.Sprint(total), nil
}
func day3AllNumbers(lines []string) []day3Number {
nums := make([]day3Number, 0)
for idxY, line := range lines {
nums = append(nums, day3NumbersFromLine(line, idxY)...)
}
return nums
}
func day3NumbersFromLine(line string, idxY int) []day3Number {
nums := make([]day3Number, 0)
matches := day3NumbersRe.FindAllStringSubmatchIndex(line, -1)
for _, match := range matches {
nums = append(nums, day3Number{
day3Point: day3Point{
idxY: idxY,
idxX: match[0],
},
len: match[1] - match[0],
})
}
return nums
}
// Runs while test is true.
func day3WalkAroundNumber(num day3Number, lines []string, test func(int, int, byte) bool) {
for y := max(0, num.idxY-1); y < min(len(lines), num.idxY+2); y++ {
for x := max(0, num.idxX-1); x < min(len(lines[num.idxY]), num.idxX+num.len+1); x++ {
if y == num.idxY && x >= num.idxX && x < num.idxX+num.len {
continue
}
if !test(y, x, lines[y][x]) {
return
}
}
}
}