code.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "regexp"
  8. "strings"
  9. )
  10. var mulRegex *regexp.Regexp = regexp.MustCompile(`mul\(\d+,\d+\)`)
  11. func getResults(line string) int {
  12. var result int
  13. matches := mulRegex.FindAllString(line, -1)
  14. for _, match := range matches {
  15. mul := make([]int, 2)
  16. n, err := fmt.Sscanf(match, "mul(%d,%d)", &mul[0], &mul[1])
  17. if n != 2 || err != nil {
  18. log.Fatalf("Bad input: %s", err)
  19. }
  20. result += mul[0] * mul[1]
  21. }
  22. return result
  23. }
  24. func readInput(file *os.File) (int, []string) {
  25. scanner := bufio.NewScanner(file)
  26. var result int
  27. var lines []string
  28. for scanner.Scan() {
  29. line := scanner.Text()
  30. if line == "" {
  31. break
  32. }
  33. lines = append(lines, line)
  34. result += getResults(line)
  35. }
  36. return result, lines
  37. }
  38. func part1(muls [][]int) int {
  39. var result int
  40. for _, mul := range muls {
  41. result += mul[0] * mul[1]
  42. }
  43. return result
  44. }
  45. func part2(lines []string) int {
  46. var result int
  47. multiply := true
  48. for _, line := range lines {
  49. var endIndex int
  50. reading := true
  51. for reading {
  52. if multiply {
  53. index := strings.Index(line, "don't()")
  54. if index == -1 {
  55. endIndex = len(line)
  56. reading = false
  57. } else {
  58. multiply = false
  59. endIndex = index
  60. }
  61. result += getResults(line[:endIndex])
  62. line = line[endIndex:]
  63. } else {
  64. index := strings.Index(line, "do()")
  65. if index == -1 {
  66. reading = false
  67. } else {
  68. multiply = true
  69. line = line[index:]
  70. }
  71. }
  72. }
  73. }
  74. return result
  75. }
  76. func main() {
  77. if len(os.Args) < 2 {
  78. log.Fatal("You need to specify a file!")
  79. }
  80. filePath := os.Args[1]
  81. file, err := os.Open(filePath)
  82. if err != nil {
  83. log.Fatalf("Failed to open %s!\n", filePath)
  84. }
  85. part1, lines := readInput(file)
  86. fmt.Println("Part1:", part1)
  87. fmt.Println("Part2:", part2(lines))
  88. }