code.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105
  1. package main
  2. import (
  3. "bufio"
  4. "fmt"
  5. "log"
  6. "os"
  7. "sort"
  8. "strings"
  9. )
  10. type Dig struct {
  11. direction string
  12. length int
  13. color string
  14. }
  15. func readInput(file *os.File) []Dig {
  16. scanner := bufio.NewScanner(file)
  17. var plan []Dig
  18. for scanner.Scan() {
  19. line := scanner.Text()
  20. if line == "" {
  21. break
  22. }
  23. var current Dig
  24. n, err := fmt.Sscanf(line, "%s %d %s", &current.direction, &current.length, &current.color)
  25. if n != 3 || err != nil {
  26. log.Fatalf("Wrong input: %s\n%s", line, err)
  27. }
  28. current.color = strings.Trim(current.color, "()")
  29. plan = append(plan, current)
  30. }
  31. return plan
  32. }
  33. type Point struct {
  34. y, x int
  35. }
  36. const (
  37. Up = "U"
  38. Down = "D"
  39. Left = "L"
  40. Right = "R"
  41. )
  42. func (p *Point) getPoints(dig Dig) []Point {
  43. var points []Point
  44. for i := 0; i < dig.length; i++ {
  45. switch dig.direction {
  46. case Up:
  47. p.y--
  48. case Down:
  49. p.y++
  50. case Left:
  51. p.x--
  52. case Right:
  53. p.x++
  54. }
  55. points = append(points, *p)
  56. }
  57. return points
  58. }
  59. func plot(plan []Dig) []Point {
  60. var current Point
  61. result := []Point{current}
  62. for i := range plan {
  63. result = append(result, current.getPoints(plan[i])...)
  64. }
  65. sort.Slice(result, func(i, j int) bool {
  66. if result[i].y == result[j].y {
  67. return result[i].x < result[j].x
  68. }
  69. return result[i].y < result[j].y
  70. })
  71. return result
  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. plan := readInput(file)
  83. fmt.Println(plot(plan))
  84. }