code.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798
  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 index >= len(equation.numbers) {
  46. if result == equation.result {
  47. return true
  48. }
  49. return false
  50. }
  51. resultAdd := check(equation, index+1, result+equation.numbers[index])
  52. resultMul := check(equation, index+1, result*equation.numbers[index])
  53. if resultAdd {
  54. return resultAdd
  55. }
  56. return resultMul
  57. }
  58. func part1(equations []Equation) int {
  59. var result int
  60. for _, equation := range equations {
  61. if check(equation, 0, 1) {
  62. result += equation.result
  63. }
  64. }
  65. return result
  66. }
  67. func main() {
  68. if len(os.Args) < 2 {
  69. log.Fatal("You need to specify a file!")
  70. }
  71. filePath := os.Args[1]
  72. file, err := os.Open(filePath)
  73. if err != nil {
  74. log.Fatalf("Failed to open %s!\n", filePath)
  75. }
  76. equations := readInput(file)
  77. fmt.Println("Part1:", part1(equations))
  78. }