package main import ( "bufio" "fmt" "log" "os" "regexp" "strconv" ) func getNum(s string) int { switch s { case "one": return 1 case "two": return 2 case "three": return 3 case "four": return 4 case "five": return 5 case "six": return 6 case "seven": return 7 case "eight": return 8 case "nine": return 9 default: n, err := strconv.Atoi(s) if err != nil { return -1 } return n } } func parseLine(line string) (int, int) { firstRe := regexp.MustCompile("([0-9]|one|two|three|four|five|six|seven|eight|nine)") lastRe := regexp.MustCompile(".*([0-9]|one|two|three|four|five|six|seven|eight|nine)") first := getNum(firstRe.FindStringSubmatch(line)[1]) last := getNum(lastRe.FindStringSubmatch(line)[1]) return first, last } func main() { fname := "input.txt" if len(os.Args) > 1 { fname = os.Args[1] } f, err := os.Open(fname) if err != nil { log.Fatal(err) } defer f.Close() sum := 0 scanner := bufio.NewScanner(f) for scanner.Scan() { line := scanner.Text() first, last := parseLine(line) if os.Getenv("DEBUG") != "" { fmt.Println(10*first + last) } sum += 10*first + last } fmt.Println(sum) if err := scanner.Err(); err != nil { log.Fatal(err) } }