code.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. )
  8. type Button struct {
  9. id byte
  10. x, y int
  11. }
  12. type Machine struct {
  13. buttons []Button
  14. x, y int
  15. }
  16. func readInput(file *os.File) []Machine {
  17. scanner := bufio.NewScanner(file)
  18. var machines []Machine
  19. var machine Machine
  20. var buttonsRead int
  21. for scanner.Scan() {
  22. line := scanner.Text()
  23. if line == "" {
  24. buttonsRead = 0
  25. machines = append(machines, machine)
  26. machine = Machine{}
  27. continue
  28. }
  29. if buttonsRead < 2 {
  30. var button Button
  31. n, err := fmt.Sscanf(line, "Button %c: X+%d, Y+%d", &button.id, &button.x, &button.y)
  32. if n != 3 || err != nil {
  33. log.Fatalf("Not able to parse button '%s': %s", line, err)
  34. }
  35. machine.buttons = append(machine.buttons, button)
  36. buttonsRead++
  37. } else {
  38. n, err := fmt.Sscanf(line, "Prize: X=%d, Y=%d", &machine.x, &machine.y)
  39. if n != 2 || err != nil {
  40. log.Fatalf("Not able to parse machine '%s': %s", line, err)
  41. }
  42. }
  43. }
  44. machines = append(machines, machine)
  45. return machines
  46. }
  47. func main() {
  48. if len(os.Args) < 2 {
  49. log.Fatal("You need to specify a file!")
  50. }
  51. filePath := os.Args[1]
  52. file, err := os.Open(filePath)
  53. if err != nil {
  54. log.Fatalf("Failed to open %s!\n", filePath)
  55. }
  56. machines := readInput(file)
  57. fmt.Println(machines)
  58. }