day3.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package main
  2. import (
  3. "flag"
  4. "fmt"
  5. "os"
  6. "regexp"
  7. "strconv"
  8. )
  9. func main() {
  10. args := flag.Bool("example", false, "example or input")
  11. flag.Parse()
  12. filename := "input.txt"
  13. if *args {
  14. filename = "example.txt"
  15. }
  16. file, err := os.Open(filename)
  17. if err != nil {
  18. fmt.Println(err)
  19. return
  20. }
  21. defer file.Close()
  22. var data []byte
  23. data, err = os.ReadFile(file.Name())
  24. if err != nil {
  25. fmt.Println(err)
  26. return
  27. }
  28. // part 1
  29. mul := regexp.MustCompile(`mul\((\d+),(\d+)\)`)
  30. matches := mul.FindAllStringSubmatch(string(data), -1)
  31. total := 0
  32. for _, match := range matches {
  33. x, err1 := strconv.Atoi(match[1])
  34. y, err2 := strconv.Atoi(match[2])
  35. if err1 == nil && err2 == nil {
  36. total += x * y
  37. }
  38. }
  39. // part 2
  40. do := regexp.MustCompile(`do`)
  41. dont := regexp.MustCompile(`don't`)
  42. isEnabled := true
  43. totalCorrected := 0
  44. cursor := 0
  45. for cursor < len(data) {
  46. if dontMatch := dont.FindIndex(data[cursor:]); dontMatch != nil && dontMatch[0] == 0 {
  47. isEnabled = false
  48. cursor += dontMatch[1]
  49. continue
  50. }
  51. if doMatch := do.FindIndex(data[cursor:]); doMatch != nil && doMatch[0] == 0 {
  52. isEnabled = true
  53. cursor += doMatch[1]
  54. continue
  55. }
  56. if mulMatch := mul.FindSubmatchIndex(data[cursor:]); mulMatch != nil && mulMatch[0] == 0 {
  57. if isEnabled {
  58. x, _ := strconv.Atoi(string(data[cursor+mulMatch[2] : cursor+mulMatch[3]]))
  59. y, _ := strconv.Atoi(string(data[cursor+mulMatch[4] : cursor+mulMatch[5]]))
  60. totalCorrected += x * y
  61. }
  62. cursor += mulMatch[1]
  63. continue
  64. }
  65. cursor++
  66. }
  67. fmt.Println("Total mul:", total)
  68. fmt.Println("Corrected Total mul:", totalCorrected)
  69. }