code.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. )
  8. type move struct {
  9. what int
  10. from int
  11. to int
  12. }
  13. func parseBoxes(line string, boxes [][]byte) [][]byte {
  14. counter := 0
  15. index := 0
  16. readLetter := false
  17. for i := range line {
  18. if line[i] == '\n' {
  19. break
  20. }
  21. counter++
  22. if counter > 3 {
  23. index++
  24. counter = 0
  25. }
  26. if line[i] == '[' {
  27. readLetter = true
  28. continue
  29. }
  30. if line[i] == ']' {
  31. readLetter = false
  32. continue
  33. }
  34. if readLetter {
  35. edge := len(boxes) - 1
  36. if index > edge {
  37. for i := 0; i < index-edge; i++ {
  38. boxes = append(boxes, []byte{})
  39. }
  40. }
  41. boxes[index] = append(boxes[index], line[i])
  42. }
  43. }
  44. return boxes
  45. }
  46. func parseMove(line string) move {
  47. var current move
  48. n, err := fmt.Sscanf(line, "move %d from %d to %d", &current.what, &current.from, &current.to)
  49. if n != 3 || err != nil {
  50. log.Fatal("Can't parse move!", err)
  51. }
  52. return current
  53. }
  54. func readInput(file *os.File) ([][]byte, []move) {
  55. scanner := bufio.NewScanner(file)
  56. var moves []move
  57. var boxes [][]byte
  58. readBoxes := true
  59. for scanner.Scan() {
  60. line := scanner.Text()
  61. if line == "" {
  62. readBoxes = false
  63. continue
  64. }
  65. if readBoxes {
  66. boxes = parseBoxes(line, boxes)
  67. continue
  68. }
  69. moves = append(moves, parseMove(line))
  70. }
  71. return boxes, moves
  72. }
  73. func main() {
  74. if len(os.Args) < 2 {
  75. log.Fatal("You need to specify a file!")
  76. }
  77. filePath := os.Args[1]
  78. file, err := os.Open(filePath)
  79. if err != nil {
  80. log.Fatalf("Failed to open %s!\n", filePath)
  81. }
  82. boxes, moves := readInput(file)
  83. fmt.Println(boxes, moves)
  84. }