code.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. )
  8. type move struct {
  9. direction byte
  10. steps int
  11. }
  12. func readInput(file *os.File) []move {
  13. scanner := bufio.NewScanner(file)
  14. var moves []move
  15. for scanner.Scan() {
  16. line := scanner.Text()
  17. if line == "" {
  18. continue
  19. }
  20. var current move
  21. n, err := fmt.Sscanf(line, "%c %d", &current.direction, &current.steps)
  22. if n != 2 || err != nil {
  23. log.Fatal("Can't parse cd:", err)
  24. }
  25. moves = append(moves, current)
  26. }
  27. return moves
  28. }
  29. type point struct {
  30. x int
  31. y int
  32. }
  33. func tailInVicinity(leader point, tail point) bool {
  34. return tail.x >= leader.x-1 && tail.x <= leader.x+1 && tail.y >= leader.y-1 && tail.y <= leader.y+1
  35. }
  36. func catchUp(leader point, tail point) point {
  37. if tailInVicinity(leader, tail) {
  38. return tail
  39. }
  40. if tail.x > leader.x {
  41. tail.x--
  42. } else if tail.x < leader.x {
  43. tail.x++
  44. }
  45. if tail.y > leader.y {
  46. tail.y--
  47. } else if tail.y < leader.y {
  48. tail.y++
  49. }
  50. return tail
  51. }
  52. func moveLead(leader point, action move) point {
  53. switch action.direction {
  54. case 'R':
  55. leader.x++
  56. return leader
  57. case 'L':
  58. leader.x--
  59. return leader
  60. case 'U':
  61. leader.y++
  62. return leader
  63. case 'D':
  64. leader.y--
  65. return leader
  66. }
  67. return leader
  68. }
  69. func wayOfTail(moves []move, snake []point) int {
  70. trail := make(map[point]bool)
  71. last := len(snake) - 1
  72. for i := range moves {
  73. for s := 0; s < moves[i].steps; s++ {
  74. for j := range snake {
  75. if j == 0 {
  76. snake[j] = moveLead(snake[j], moves[i])
  77. } else {
  78. snake[j] = catchUp(snake[j-1], snake[j])
  79. }
  80. }
  81. trail[snake[last]] = true
  82. }
  83. }
  84. return len(trail)
  85. }
  86. func main() {
  87. if len(os.Args) < 2 {
  88. log.Fatal("You need to specify a file!")
  89. }
  90. filePath := os.Args[1]
  91. file, err := os.Open(filePath)
  92. if err != nil {
  93. log.Fatalf("Failed to open %s!\n", filePath)
  94. }
  95. moves := readInput(file)
  96. snake1 := make([]point, 2)
  97. fmt.Println("Part1:", wayOfTail(moves, snake1))
  98. snake2 := make([]point, 10)
  99. fmt.Println("Part2:", wayOfTail(moves, snake2))
  100. }