code.go 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109
  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 startIndex, 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[startIndex:endIndex])
  62. line = line[endIndex:]
  63. startIndex = 0
  64. } else {
  65. index := strings.Index(line, "do()")
  66. if index == -1 {
  67. reading = false
  68. } else {
  69. multiply = true
  70. startIndex = 0
  71. line = line[index:]
  72. }
  73. }
  74. }
  75. }
  76. return result
  77. }
  78. func main() {
  79. if len(os.Args) < 2 {
  80. log.Fatal("You need to specify a file!")
  81. }
  82. filePath := os.Args[1]
  83. file, err := os.Open(filePath)
  84. if err != nil {
  85. log.Fatalf("Failed to open %s!\n", filePath)
  86. }
  87. part1, lines := readInput(file)
  88. fmt.Println("Part1:", part1)
  89. fmt.Println("Part2:", part2(lines))
  90. }