code.go 823 B

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "regexp"
  8. )
  9. func readInput(file *os.File) [][]int {
  10. scanner := bufio.NewScanner(file)
  11. var muls [][]int
  12. for scanner.Scan() {
  13. line := scanner.Text()
  14. if line == "" {
  15. break
  16. }
  17. re := regexp.MustCompile(`mul\(\d+,\d+\)`)
  18. matches := re.FindAllString(line, -1)
  19. for _, match := range matches {
  20. mul := make([]int, 2)
  21. n, err := fmt.Sscanf(match, "mul(%d,%d)", &mul[0], &mul[1])
  22. if n != 2 || err != nil {
  23. log.Fatalf("Bad input: %s", err)
  24. }
  25. muls = append(muls, mul)
  26. }
  27. }
  28. return muls
  29. }
  30. func main() {
  31. if len(os.Args) < 2 {
  32. log.Fatal("You need to specify a file!")
  33. }
  34. filePath := os.Args[1]
  35. file, err := os.Open(filePath)
  36. if err != nil {
  37. log.Fatalf("Failed to open %s!\n", filePath)
  38. }
  39. muls := readInput(file)
  40. fmt.Println(muls)
  41. }