-
Notifications
You must be signed in to change notification settings - Fork 0
/
day01.go
93 lines (78 loc) · 1.67 KB
/
day01.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
package main
import (
_ "embed"
"fmt"
"strings"
)
//go:embed input.txt
var input string
func part1(input string) int {
lines := strings.Split(input, "\n")
var first, last, sum int
for _, line := range lines {
for i := range line {
if line[i] >= '1' && line[i] <= '9' {
first = int(line[i] - '0')
break
}
}
for i := len(line) - 1; i >= 0; i-- {
if line[i] >= '1' && line[i] <= '9' {
last = int(line[i] - '0')
break
}
}
sum += first*10 + last
}
return sum
}
func part2(input string) int {
lines := strings.Split(input, "\n")
digits := []string{"one", "two", "three", "four", "five", "six", "seven", "eight", "nine"}
var first, last, sum int
for _, line := range lines {
FirstLoop:
for i := 0; i < len(line); i++ {
b := line[i]
if b >= '1' && b <= '9' {
first = int(b - '0')
break
}
if b == 'e' || b == 'f' || b == 'n' || b == 'o' || b == 's' || b == 't' {
for j, digit := range digits {
for k := 0; line[i+k] == digit[k]; k++ {
if len(digit)-1 == k {
first = j + 1
break FirstLoop
}
}
}
}
}
LastLoop:
for i := len(line) - 1; i >= 0; i-- {
b := line[i]
if b >= '1' && b <= '9' {
last = int(b - '0')
break
}
if b == 'e' || b == 'n' || b == 'o' || b == 'r' || b == 't' || b == 'x' {
for j, digit := range digits {
for k := 0; line[i-k] == digit[len(digit)-1-k]; k++ {
if len(digit)-1 == k {
last = j + 1
break LastLoop
}
}
}
}
}
sum += first*10 + last
}
return sum
}
func main() {
fmt.Println("--- 2023 day 01 answer ---")
fmt.Println("part 1:\t", part1(input))
fmt.Println("part 2:\t", part2(input))
}