day16.go 2.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122
  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. parts := strings.Split(line, ":")
  19. if len(parts) != 2 {
  20. log.Fatalf("Invalid line: %s", line)
  21. }
  22. newRule.name = parts[0]
  23. n, err := fmt.Sscanf(parts[1], "%d-%d or %d-%d\n", &newRule.firstSegment[0], &newRule.firstSegment[1], &newRule.secondSegment[0], &newRule.secondSegment[1])
  24. if err != nil || n != 4 {
  25. log.Fatalf("Error scanning '%s': %s", line, err)
  26. }
  27. rules = append(rules, newRule)
  28. }
  29. type ticket []int
  30. var tickets []ticket
  31. func readTicket(line string) {
  32. var newTicket ticket
  33. for _, item := range strings.Split(line, ",") {
  34. field, err := strconv.Atoi(item)
  35. if err != nil {
  36. log.Fatalf("Error parsing field from %s: %s", item, err)
  37. }
  38. newTicket = append(newTicket, field)
  39. }
  40. tickets = append(tickets, newTicket)
  41. }
  42. func readFile(file *os.File) {
  43. scanner := bufio.NewScanner(file)
  44. currentFunction := readRule
  45. for scanner.Scan() {
  46. line := scanner.Text()
  47. if line == "" {
  48. continue
  49. }
  50. if strings.Contains(line, "your ticket:") {
  51. currentFunction = readTicket
  52. continue
  53. }
  54. if strings.Contains(line, "nearby tickets:") {
  55. continue
  56. }
  57. currentFunction(line)
  58. }
  59. if err := scanner.Err(); err != nil {
  60. log.Fatalf("Scanner error: %s", err)
  61. }
  62. }
  63. func checkAllRulesOnField(field int) bool {
  64. for _, currentRule := range rules {
  65. if (field >= currentRule.firstSegment[0] && field <= currentRule.firstSegment[1]) || (field >= currentRule.secondSegment[0] && field <= currentRule.secondSegment[1]) {
  66. return true
  67. }
  68. }
  69. return false
  70. }
  71. func sumBad() int {
  72. numberOfTickets := len(tickets)
  73. sum := 0
  74. for i := 1; i < numberOfTickets; i++ {
  75. for _, field := range tickets[i] {
  76. if !checkAllRulesOnField(field) {
  77. sum += field
  78. }
  79. }
  80. }
  81. return sum
  82. }
  83. func main() {
  84. if len(os.Args) < 2 {
  85. log.Fatal("You need to specify a file!")
  86. }
  87. filePath := os.Args[1]
  88. file, err := os.Open(filePath)
  89. if err != nil {
  90. log.Fatalf("Failed to open %s!\n", filePath)
  91. }
  92. readFile(file)
  93. if err := file.Close(); err != nil {
  94. log.Fatalf("Failed to close file: %s", err)
  95. }
  96. fmt.Println("Part1:", sumBad())
  97. }