Skip to content

Commit e163659

Browse files
feat(day01): solve part02
1 parent 2a15632 commit e163659

File tree

1 file changed

+52
-12
lines changed

1 file changed

+52
-12
lines changed

2023-go/day01/day01.go

+52-12
Original file line numberDiff line numberDiff line change
@@ -59,25 +59,65 @@ func partTwo(lines []string) {
5959

6060
// please create a function that solves the problem
6161
func readCalibrationValue2(line string) int {
62+
var firstDigit int
63+
var lastDigit int
6264
digits := map[string]int{
63-
"one": 1,
64-
"two": 2,
65-
"three": 3,
66-
"four": 4,
67-
"five": 5,
68-
"six": 6,
69-
"seven": 7,
70-
"eight": 8,
71-
"nine": 9,
65+
"one": 49,
66+
"two": 50,
67+
"three": 51,
68+
"four": 52,
69+
"five": 53,
70+
"six": 54,
71+
"seven": 55,
72+
"eight": 56,
73+
"nine": 57,
7274
}
7375

7476
// search for first occurrence of spelled out digit or actual digit
75-
for i := 0; i < len(line); i++ {
77+
firstDigit = searchForCalibrationValueFromLeftToRight(line, digits)
7678

77-
}
78-
return 0
79+
lastDigit = searchForCalibrationValueFromRightToLeft(line, digits)
80+
81+
n, _ := strconv.Atoi(string(rune(firstDigit)) + "" + string(rune(lastDigit)))
82+
return n
7983
}
8084

8185
func isActualDigit(char int) bool {
8286
return char >= '1' && char <= '9'
8387
}
88+
89+
func searchForCalibrationValueFromLeftToRight(line string, digits map[string]int) int {
90+
for i := 0; i < len(line); i++ {
91+
for j, k := range digits {
92+
if len(j)+i <= len(line) {
93+
word := line[i : i+len(j)]
94+
if word == j {
95+
return k
96+
}
97+
}
98+
}
99+
char := int(line[i])
100+
if isActualDigit(char) {
101+
return char
102+
}
103+
}
104+
return 0
105+
}
106+
107+
func searchForCalibrationValueFromRightToLeft(line string, digits map[string]int) int {
108+
for i := len(line) - 1; i >= 0; i-- {
109+
for j, k := range digits {
110+
if i-len(j) >= 0 {
111+
word := line[i-len(j)+1 : i+1]
112+
if word == j {
113+
return k
114+
}
115+
}
116+
}
117+
char := int(line[i])
118+
if isActualDigit(char) {
119+
return char
120+
}
121+
}
122+
return 0
123+
}

0 commit comments

Comments
 (0)