code.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. )
  8. type Point struct {
  9. y, x int
  10. }
  11. func findRobot(line string) *Point {
  12. for i, char := range line {
  13. if char == '@' {
  14. return &Point{x: i}
  15. }
  16. }
  17. return nil
  18. }
  19. func readInput(file *os.File) (*Point, [][]byte, []byte) {
  20. scanner := bufio.NewScanner(file)
  21. var matrix [][]byte
  22. var moves []byte
  23. var robot *Point
  24. var y int
  25. readingMatrix := true
  26. for scanner.Scan() {
  27. line := scanner.Text()
  28. if line == "" {
  29. if readingMatrix {
  30. readingMatrix = false
  31. continue
  32. }
  33. break
  34. }
  35. if readingMatrix {
  36. matrix = append(matrix, []byte(line))
  37. if robot == nil {
  38. robot = findRobot(line)
  39. if robot != nil {
  40. robot.y = y
  41. }
  42. y++
  43. }
  44. } else {
  45. moves = append(moves, []byte(line)...)
  46. }
  47. }
  48. return robot, matrix, moves
  49. }
  50. func moveBox(x, y int, matrix [][]byte, xPlus, yPlus int) bool {
  51. field := matrix[y][x]
  52. if field == '#' {
  53. return false
  54. }
  55. if field == 'O' {
  56. if !moveBox(x+xPlus, y+yPlus, matrix, xPlus, yPlus) {
  57. return false
  58. }
  59. }
  60. matrix[y][x] = 'O'
  61. return true
  62. }
  63. func moveRobot(robot *Point, matrix [][]byte, x, y int) {
  64. matrix[robot.y][robot.x] = '.'
  65. field := matrix[robot.y+y][robot.x+x]
  66. if field == '#' {
  67. return
  68. }
  69. if field == 'O' {
  70. if !moveBox(robot.x+x, robot.y+y, matrix, x, y) {
  71. return
  72. }
  73. }
  74. robot.x += x
  75. robot.y += y
  76. }
  77. func processMoves(robot *Point, matrix [][]byte, moves []byte) {
  78. for _, move := range moves {
  79. switch move {
  80. case '^':
  81. moveRobot(robot, matrix, 0, -1)
  82. fmt.Println(robot, matrix)
  83. case 'v':
  84. moveRobot(robot, matrix, 0, 1)
  85. fmt.Println(robot, matrix)
  86. case '<':
  87. moveRobot(robot, matrix, -1, 0)
  88. fmt.Println(robot, matrix)
  89. case '>':
  90. moveRobot(robot, matrix, 1, 0)
  91. fmt.Println(robot, matrix)
  92. }
  93. }
  94. }
  95. func main() {
  96. if len(os.Args) < 2 {
  97. log.Fatal("You need to specify a file!")
  98. }
  99. filePath := os.Args[1]
  100. file, err := os.Open(filePath)
  101. if err != nil {
  102. log.Fatalf("Failed to open %s!\n", filePath)
  103. }
  104. robot, matrix, moves := readInput(file)
  105. processMoves(robot, matrix, moves)
  106. }