@@ -62,23 +62,23 @@ func part1(input string) int {
6262 return total
6363}
6464
65+ var prefixes map [string ]int = map [string ]int {
66+ "one" : 1 ,
67+ "two" : 2 ,
68+ "three" : 3 ,
69+ "four" : 4 ,
70+ "five" : 5 ,
71+ "six" : 6 ,
72+ "seven" : 7 ,
73+ "eight" : 8 ,
74+ "nine" : 9 ,
75+ "zero" : 0 ,
76+ }
77+
6578func part2 (input string ) int {
6679 parsed := parseInput (input )
6780 total := 0
6881
69- prefixes := map [string ]int {
70- "one" : 1 ,
71- "two" : 2 ,
72- "three" : 3 ,
73- "four" : 4 ,
74- "five" : 5 ,
75- "six" : 6 ,
76- "seven" : 7 ,
77- "eight" : 8 ,
78- "nine" : 9 ,
79- "zero" : 0 ,
80- }
81-
8282 for _ , line := range parsed {
8383 first := - 1
8484 last := - 1
@@ -93,15 +93,23 @@ func part2(input string) int {
9393 }
9494 last = num
9595 } else {
96- for prefix , val := range prefixes {
97- if checkPrefix (line [i :], prefix ) {
96+ // the number names range from 3 to 5 in length so we just need
97+ // to check those three lengths in the map
98+ for j := 3 ; j < 6 ; j ++ {
99+ end := i + j
100+ // If we are over the end of the string, no point in checking
101+ if end > len (line ) {
102+ break
103+ }
104+ val , ok := prefixes [line [i :end ]]
105+ if ok {
98106 if first == - 1 {
99107 first = val
100108 }
101109 last = val
102110
103111 // jump forward to the last letter of the prefix
104- i += len ( prefix ) - 2
112+ i += j - 2
105113 break
106114 }
107115 }
@@ -117,10 +125,3 @@ func part2(input string) int {
117125func parseInput (input string ) (ans []string ) {
118126 return strings .Split (input , "\n " )
119127}
120-
121- func checkPrefix (str string , prefix string ) bool {
122- if len (str ) < len (prefix ) {
123- return false
124- }
125- return str [:len (prefix )] == prefix
126- }
0 commit comments