day16.go 1.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "strconv"
  8. "strings"
  9. )
  10. type rule struct {
  11. name string
  12. firstSegment [2]int
  13. secondSegment [2]int
  14. }
  15. var rules []rule
  16. func readRule(line string) {
  17. var newRule rule
  18. n, err := fmt.Sscanf(line, "%s %d-%d or %d-%d\n", &newRule.name, &newRule.firstSegment[0], &newRule.firstSegment[1], &newRule.secondSegment[0], &newRule.secondSegment[1])
  19. if err != nil || n != 5 {
  20. log.Fatalf("Error scanning '%s': %s", line, err)
  21. }
  22. rules = append(rules, newRule)
  23. }
  24. type ticket []int64
  25. var tickets []ticket
  26. func readTicket(line string) {
  27. var newTicket ticket
  28. for _, item := range strings.Split(line, ",") {
  29. field, err := strconv.ParseInt(item, 10, 32)
  30. if err != nil {
  31. log.Fatalf("Error parsing field from %s: %s", item, err)
  32. }
  33. newTicket = append(newTicket, field)
  34. }
  35. tickets = append(tickets, newTicket)
  36. }
  37. func readFile(file *os.File) {
  38. scanner := bufio.NewScanner(file)
  39. index := 0
  40. for scanner.Scan() {
  41. line := scanner.Text()
  42. if line == "" {
  43. continue
  44. }
  45. if strings.Contains(line, "your ticket:") {
  46. index++
  47. continue
  48. }
  49. if strings.Contains(line, "nearby tickets:") {
  50. continue
  51. }
  52. functions[index](line)
  53. }
  54. if err := scanner.Err(); err != nil {
  55. log.Fatalf("Scanner error: %s", err)
  56. }
  57. }
  58. var functions []func(string)
  59. func init() {
  60. functions = append(functions, readRule)
  61. functions = append(functions, readTicket)
  62. }
  63. func main() {
  64. if len(os.Args) < 2 {
  65. log.Fatal("You need to specify a file!")
  66. }
  67. filePath := os.Args[1]
  68. file, err := os.Open(filePath)
  69. if err != nil {
  70. log.Fatalf("Failed to open %s!\n", filePath)
  71. }
  72. readFile(file)
  73. if err := file.Close(); err != nil {
  74. log.Fatalf("Failed to close file: %s", err)
  75. }
  76. fmt.Println(rules)
  77. fmt.Println(tickets)
  78. }