-
Notifications
You must be signed in to change notification settings - Fork 0
/
day.go
97 lines (83 loc) · 1.62 KB
/
day.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
package main
import (
"embed"
"log"
"strconv"
"strings"
"unicode"
"github.com/drudge/go-advent-of-code/pkg/aoc"
)
//go:embed input.txt
var inputFile embed.FS
var digitMap = []string{
"zero",
"one",
"two",
"three",
"four",
"five",
"six",
"seven",
"eight",
"nine",
}
func parseNumbers(line string, includeAlpha bool) string {
var firstDigit, lastDigit string
var firstIndex, lastIndex = len(line), -1
for i := 0; i < len(line); i++ {
if includeAlpha && unicode.IsLetter(rune(line[i])) {
for digit, word := range digitMap {
if strings.HasPrefix(line[i:], word) {
index := i + len(word) - 1
digitStr := strconv.Itoa(digit)
if firstIndex > i {
firstDigit = digitStr
firstIndex = i
}
if lastIndex < index {
lastDigit = digitStr
lastIndex = index
}
i = index
break
}
}
} else if unicode.IsDigit(rune(line[i])) {
digitStr := string(line[i])
if firstIndex > i {
firstDigit = digitStr
firstIndex = i
}
if lastIndex < i {
lastDigit = digitStr
lastIndex = i
}
}
}
if firstIndex == len(line) {
return ""
}
return firstDigit + lastDigit
}
func partOne(input []string) int {
sum := 0
for _, line := range input {
sum += aoc.ToInt(parseNumbers(line, false))
}
return sum
}
func partTwo(input []string) int {
sum := 0
for i, line := range input {
parsed := parseNumbers(line, true)
log.Printf("[%v] line: %v, parsed: %v\n", i, line, parsed)
if parsed != "" {
sum += aoc.ToInt(parsed)
}
}
return sum
}
func main() {
lines := aoc.GetDayInput(inputFile)
aoc.RunSolution(lines, partOne, partTwo)
}