-
Notifications
You must be signed in to change notification settings - Fork 0
/
day1.go
95 lines (87 loc) · 1.67 KB
/
day1.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
package main
import (
"errors"
"strings"
"unicode"
)
var digitWordMap = map[string]int{
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9,
}
var notFoundErr = errors.New("404: Not found")
type Day1 struct {
filePath string
}
func (Day1) Name() string {
return "day1"
}
func (day Day1) FilePath() string {
return day.filePath
}
func (Day1) Part1(lines []string) (int, error) {
calculateLine := func(line string) int {
first_digit := 0
last_digit := 0
found_first := false
for _, char := range line {
if !unicode.IsDigit(char) {
continue
}
digit := int(char - '0')
if !found_first {
first_digit = digit
}
last_digit = digit
found_first = true
}
return (first_digit * 10) + last_digit
}
total := 0
for _, line := range lines {
total += calculateLine(line)
}
return total, nil
}
func (Day1) Part2(lines []string) (int, error) {
extractDigit := func(line string, i int, char rune) (int, error) {
if unicode.IsDigit(char) {
return int(char - '0'), nil
}
// Inefficient. I don't care.
for word, val := range digitWordMap {
if strings.HasPrefix(line[i:], word) {
return val, nil
}
}
return 0, notFoundErr
}
calculateLine := func(line string) int {
first_digit := 0
last_digit := 0
found_first := false
for i, char := range line {
digit, err := extractDigit(line, i, char)
if err != nil {
continue
}
if !found_first {
first_digit = digit
}
last_digit = digit
found_first = true
}
return (first_digit * 10) + last_digit
}
total := 0
for _, line := range lines {
total += calculateLine(line)
}
return total, nil
}