code.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  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. re := regexp.MustCompile(`mul\(\d+,\d+\)`)
  49. for _, line := range lines {
  50. var startIndex, endIndex int
  51. reading := true
  52. for reading {
  53. if multiply {
  54. index := strings.Index(line, "don't()")
  55. if index == -1 {
  56. endIndex = len(line)
  57. reading = false
  58. } else {
  59. multiply = false
  60. endIndex = index
  61. }
  62. if startIndex > endIndex {
  63. startIndex++
  64. continue
  65. }
  66. matches := re.FindAllString(line[startIndex:endIndex], -1)
  67. for _, match := range matches {
  68. mul := make([]int, 2)
  69. n, err := fmt.Sscanf(match, "mul(%d,%d)", &mul[0], &mul[1])
  70. if n != 2 || err != nil {
  71. log.Fatalf("Bad input: %s", err)
  72. }
  73. result += mul[0] * mul[1]
  74. }
  75. line = line[endIndex:]
  76. startIndex = 0
  77. } else {
  78. index := strings.Index(line, "do()")
  79. if index == -1 {
  80. reading = false
  81. } else {
  82. multiply = true
  83. startIndex = 0
  84. line = line[index:]
  85. }
  86. }
  87. }
  88. }
  89. return result
  90. }
  91. func main() {
  92. if len(os.Args) < 2 {
  93. log.Fatal("You need to specify a file!")
  94. }
  95. filePath := os.Args[1]
  96. file, err := os.Open(filePath)
  97. if err != nil {
  98. log.Fatalf("Failed to open %s!\n", filePath)
  99. }
  100. part1, lines := readInput(file)
  101. fmt.Println("Part1:", part1)
  102. fmt.Println("Part2:", part2(lines))
  103. }