-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathday1.go
More file actions
75 lines (68 loc) · 1.4 KB
/
day1.go
File metadata and controls
75 lines (68 loc) · 1.4 KB
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
package main
import (
"fmt"
"regexp"
"strconv"
"strings"
)
func day1(input string) int {
total := 0
reg := regexp.MustCompile(`(\d)`)
fromInput(input, func(line string) {
digits := reg.FindAllStringSubmatch(line, -1)
first := digits[0][0]
last := digits[len(digits)-1][0]
number, err := strconv.Atoi(fmt.Sprintf("%s%s", first, last))
if err != nil {
panic(err)
}
total += number
})
return total
}
var numberMapping = map[string]int{
"one": 1,
"two": 2,
"three": 3,
"four": 4,
"five": 5,
"six": 6,
"seven": 7,
"eight": 8,
"nine": 9,
}
var neededs = []string{"one", "two", "three", "four", "five", "six", "seven", "eight", "nine", "1", "2", "3", "4", "5", "6", "7", "8", "9"}
func day1_2(input string) int {
total := 0
fromInput(input, func(line string) {
first := ""
lowerIndex := len(line)
greaterIndex := 0
last := ""
for _, n := range neededs {
lastV := strings.LastIndex(line, n)
firstV := strings.Index(line, n)
if firstV != -1 && firstV <= lowerIndex {
lowerIndex = firstV
first = n
}
if lastV != -1 && lastV >= greaterIndex {
greaterIndex = lastV
last = n
}
}
number, err := strconv.Atoi(fmt.Sprintf("%d%d", getDigit(first), getDigit(last)))
if err != nil {
panic(err)
}
total += number
})
return total
}
func getDigit(v string) int {
iv, err := strconv.Atoi(v)
if err != nil {
iv = numberMapping[v]
}
return iv
}