aoc

Advent of Code Solutions
git clone git://git.alexkarle.com.com/aoc
Log | Files | Refs | README | LICENSE

2.go (1239B) [raw]


      1 package main
      2 
      3 import (
      4 	"bufio"
      5 	"fmt"
      6 	"log"
      7 	"os"
      8 	"regexp"
      9 	"strconv"
     10 )
     11 
     12 func getNum(s string) int {
     13 	switch s {
     14 	case "one":
     15 		return 1
     16 	case "two":
     17 		return 2
     18 	case "three":
     19 		return 3
     20 	case "four":
     21 		return 4
     22 	case "five":
     23 		return 5
     24 	case "six":
     25 		return 6
     26 	case "seven":
     27 		return 7
     28 	case "eight":
     29 		return 8
     30 	case "nine":
     31 		return 9
     32 	default:
     33 		n, err := strconv.Atoi(s)
     34 		if err != nil {
     35 			return -1
     36 		}
     37 		return n
     38 	}
     39 }
     40 
     41 func parseLine(line string) (int, int) {
     42 	firstRe := regexp.MustCompile("([0-9]|one|two|three|four|five|six|seven|eight|nine)")
     43 	lastRe := regexp.MustCompile(".*([0-9]|one|two|three|four|five|six|seven|eight|nine)")
     44 	first := getNum(firstRe.FindStringSubmatch(line)[1])
     45 	last := getNum(lastRe.FindStringSubmatch(line)[1])
     46 
     47 	return first, last
     48 }
     49 
     50 func main() {
     51 	fname := "input.txt"
     52 	if len(os.Args) > 1 {
     53 		fname = os.Args[1]
     54 	}
     55 	f, err := os.Open(fname)
     56 	if err != nil {
     57 		log.Fatal(err)
     58 	}
     59 	defer f.Close()
     60 
     61 	sum := 0
     62 	scanner := bufio.NewScanner(f)
     63 	for scanner.Scan() {
     64 		line := scanner.Text()
     65 		first, last := parseLine(line)
     66 		if os.Getenv("DEBUG") != "" {
     67 			fmt.Println(10*first + last)
     68 		}
     69 		sum += 10*first + last
     70 	}
     71 	fmt.Println(sum)
     72 
     73 	if err := scanner.Err(); err != nil {
     74 		log.Fatal(err)
     75 	}
     76 }