code.go 1.4 KB

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