code.go 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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 main() {
  45. if len(os.Args) < 2 {
  46. log.Fatal("You need to specify a file!")
  47. }
  48. filePath := os.Args[1]
  49. file, err := os.Open(filePath)
  50. if err != nil {
  51. log.Fatalf("Failed to open %s!\n", filePath)
  52. }
  53. equations := readInput(file)
  54. fmt.Println(equations)
  55. }