day16.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. )
  8. type rule struct {
  9. name string
  10. firstSegment [2]int
  11. secondSegment [2]int
  12. }
  13. var rules []rule
  14. func readRule(line string) {
  15. var newRule rule
  16. 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])
  17. if err != nil || n != 5 {
  18. log.Fatalf("Error scanning '%s': %s", line, err)
  19. }
  20. rules = append(rules, newRule)
  21. }
  22. func readFile(file *os.File) {
  23. scanner := bufio.NewScanner(file)
  24. for scanner.Scan() {
  25. line := scanner.Text()
  26. if line == "" {
  27. break
  28. }
  29. readRule(line)
  30. }
  31. if err := scanner.Err(); err != nil {
  32. log.Fatalf("Scanner error: %s", err)
  33. }
  34. }
  35. func main() {
  36. if len(os.Args) < 2 {
  37. log.Fatal("You need to specify a file!")
  38. }
  39. filePath := os.Args[1]
  40. file, err := os.Open(filePath)
  41. if err != nil {
  42. log.Fatalf("Failed to open %s!\n", filePath)
  43. }
  44. readFile(file)
  45. if err := file.Close(); err != nil {
  46. log.Fatalf("Failed to close file: %s", err)
  47. }
  48. fmt.Println(rules)
  49. }