package main import ( "flag" "fmt" "os" "regexp" "strconv" "strings" ) var ( inputFile = flag.String("input", "input.txt", "input filename") nRegex = regexp.MustCompile(`(?m)\d`) reMap = map[string]string{ "one": "1", "two": "2", "three": "3", "four": "4", "five": "5", "six": "6", "seven": "7", "eight": "8", "nine": "9", } ) func main() { flag.Parse() input, err := os.ReadFile(*inputFile) if err != nil { panic(err) } var sum int for _, line := range strings.Split(string(input), "\n") { if strings.TrimSpace(line) == "" { continue } // forward-scan for spelled digits var forwardReplacedLine, backwardReplacedLine string for i := 0; i < len(line); i++ { forwardReplacedLine += string(line[i]) // replace all potential spelled out digits by their non-word counterpart (e.g. "one" -> "1") for key, val := range reMap { forwardReplacedLine = strings.ReplaceAll(forwardReplacedLine, key, val) } } fmt.Println(forwardReplacedLine) // backward-scan for spelled digits for i := len(line) - 1; i >= 0; i-- { if i == len(line)-1 { backwardReplacedLine = string(line[i]) } else { backwardReplacedLine = string(line[i]) + backwardReplacedLine } // replace all potential spelled out digits by their non-word counterpart (e.g. "one" -> "1") for key, val := range reMap { backwardReplacedLine = strings.ReplaceAll(backwardReplacedLine, key, val) } } fmt.Println(backwardReplacedLine) // find single digits in forward-replaced line firstMatch := nRegex.FindAllStringSubmatch(forwardReplacedLine, -1) // find single digits in backward-replaced line lastMatch := nRegex.FindAllStringSubmatch(backwardReplacedLine, -1) // get first match, first matchgroup (aka first digit in forwardReplacedLine) first := firstMatch[0][0] // get last match, first matchgroup (aka last digit in backwardReplacedLine) last := lastMatch[len(lastMatch)-1:][0][0] fmt.Println(first + last) // concatenate digits and convert the resulting string to int asInt, err := strconv.Atoi(first + last) if err != nil { panic(err) } sum += asInt } fmt.Println(sum) }