@@ -59,25 +59,65 @@ func partTwo(lines []string) {
59
59
60
60
// please create a function that solves the problem
61
61
func readCalibrationValue2 (line string ) int {
62
+ var firstDigit int
63
+ var lastDigit int
62
64
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 ,
72
74
}
73
75
74
76
// search for first occurrence of spelled out digit or actual digit
75
- for i := 0 ; i < len (line ); i ++ {
77
+ firstDigit = searchForCalibrationValueFromLeftToRight (line , digits )
76
78
77
- }
78
- return 0
79
+ lastDigit = searchForCalibrationValueFromRightToLeft (line , digits )
80
+
81
+ n , _ := strconv .Atoi (string (rune (firstDigit )) + "" + string (rune (lastDigit )))
82
+ return n
79
83
}
80
84
81
85
func isActualDigit (char int ) bool {
82
86
return char >= '1' && char <= '9'
83
87
}
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