code.go 1.2 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "strings"
  8. )
  9. type Directions struct {
  10. left string
  11. right string
  12. }
  13. type Network struct {
  14. moves string
  15. paths map[string]Directions
  16. }
  17. func readInput(file *os.File) Network {
  18. scanner := bufio.NewScanner(file)
  19. var network Network
  20. readMoves := false
  21. for scanner.Scan() {
  22. line := scanner.Text()
  23. if line == "" {
  24. if !readMoves {
  25. readMoves = true
  26. continue
  27. }
  28. break
  29. }
  30. if !readMoves {
  31. network.moves = line
  32. network.paths = make(map[string]Directions)
  33. } else {
  34. fromParts := strings.Split(line, " = ")
  35. if len(fromParts) != 2 {
  36. log.Fatalf("Wrong number of fromParts: %s", line)
  37. }
  38. from := fromParts[0]
  39. parts := strings.Split(fromParts[1], ", ")
  40. if len(parts) != 2 {
  41. log.Fatalf("Wrong number of parts: %s", fromParts[1])
  42. }
  43. var directions Directions
  44. directions.left = parts[0]
  45. directions.right = parts[1]
  46. network.paths[from] = directions
  47. }
  48. }
  49. return network
  50. }
  51. func main() {
  52. if len(os.Args) < 2 {
  53. log.Fatal("You need to specify a file!")
  54. }
  55. filePath := os.Args[1]
  56. file, err := os.Open(filePath)
  57. if err != nil {
  58. log.Fatalf("Failed to open %s!\n", filePath)
  59. }
  60. network := readInput(file)
  61. fmt.Println(network)
  62. }