code.go 1.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100
  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 = strings.TrimLeft(parts[0], "(")
  45. directions.right = strings.TrimRight(parts[1], ")")
  46. network.paths[from] = directions
  47. }
  48. }
  49. return network
  50. }
  51. func part1(network Network) int {
  52. steps := 0
  53. current := "AAA"
  54. mod := len(network.moves)
  55. index := 0
  56. for {
  57. if current == "ZZZ" {
  58. break
  59. }
  60. d := network.paths[current]
  61. if network.moves[index] == 'L' {
  62. current = d.left
  63. } else {
  64. current = d.right
  65. }
  66. index = (index + 1) % mod
  67. steps++
  68. }
  69. return steps
  70. }
  71. func main() {
  72. if len(os.Args) < 2 {
  73. log.Fatal("You need to specify a file!")
  74. }
  75. filePath := os.Args[1]
  76. file, err := os.Open(filePath)
  77. if err != nil {
  78. log.Fatalf("Failed to open %s!\n", filePath)
  79. }
  80. network := readInput(file)
  81. fmt.Println("Part1:", part1(network))
  82. }