code.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "strconv"
  8. "strings"
  9. )
  10. type Equation struct {
  11. result int
  12. numbers []int
  13. }
  14. func readInput(file *os.File) []Equation {
  15. scanner := bufio.NewScanner(file)
  16. var equations []Equation
  17. for scanner.Scan() {
  18. line := scanner.Text()
  19. if line == "" {
  20. break
  21. }
  22. var equation Equation
  23. parts := strings.Split(line, ": ")
  24. if len(parts) != 2 {
  25. log.Fatalf("Bad input: %s", line)
  26. }
  27. var err error
  28. equation.result, err = strconv.Atoi(parts[0])
  29. if err != nil {
  30. log.Fatalf("Problem parsing '%s': %s", parts[0], err)
  31. }
  32. numbers := strings.Split(parts[1], " ")
  33. for _, number := range numbers {
  34. item, err := strconv.Atoi(number)
  35. if err != nil {
  36. log.Fatalf("Problem parsing '%s': %s", number, err)
  37. }
  38. equation.numbers = append(equation.numbers, item)
  39. }
  40. equations = append(equations, equation)
  41. }
  42. return equations
  43. }
  44. func check(equation Equation, index, result int) bool {
  45. if result > equation.result {
  46. return false
  47. }
  48. if index >= len(equation.numbers) {
  49. if result == equation.result {
  50. return true
  51. }
  52. return false
  53. }
  54. resultAdd := check(equation, index+1, result+equation.numbers[index])
  55. resultMul := check(equation, index+1, result*equation.numbers[index])
  56. if resultAdd {
  57. return resultAdd
  58. }
  59. return resultMul
  60. }
  61. func part1(equations []Equation) int {
  62. var result int
  63. for _, equation := range equations {
  64. if check(equation, 0, 1) {
  65. result += equation.result
  66. }
  67. }
  68. return result
  69. }
  70. func main() {
  71. if len(os.Args) < 2 {
  72. log.Fatal("You need to specify a file!")
  73. }
  74. filePath := os.Args[1]
  75. file, err := os.Open(filePath)
  76. if err != nil {
  77. log.Fatalf("Failed to open %s!\n", filePath)
  78. }
  79. equations := readInput(file)
  80. fmt.Println("Part1:", part1(equations))
  81. }