d01.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106
  1. package main
  2. import "container/list"
  3. import "strings"
  4. import "strconv"
  5. import "bufio"
  6. import "math"
  7. import "fmt"
  8. import "os"
  9. type Vect struct {
  10. posX int
  11. posY int
  12. head int
  13. }
  14. func (this *Vect) addStepCount() {
  15. switch this.head {
  16. case 0:
  17. this.posY++
  18. break
  19. case 1:
  20. this.posX++
  21. break
  22. case 2:
  23. this.posY--
  24. break;
  25. case 3:
  26. this.posX--
  27. break
  28. }
  29. }
  30. func (this *Vect) addStep(dir string) bool {
  31. if dir == "R" {
  32. this.head++;
  33. for this.head >= 4 { this.head -= 4 }
  34. } else if dir == "L" {
  35. this.head--;
  36. for this.head < 0 { this.head += 4 }
  37. } else {
  38. return false
  39. }
  40. return true
  41. }
  42. func (this Vect) toTaxiCab() int {
  43. return int(math.Abs(float64(this.posX)) +
  44. math.Abs(float64(this.posY)))
  45. }
  46. func (this Vect) inList(list list.List) bool {
  47. for e := list.Front(); e != nil; e = e.Next() {
  48. if e.Value.(Vect).posX == this.posX &&
  49. e.Value.(Vect).posY == this.posY {
  50. return true
  51. }
  52. }
  53. return false
  54. }
  55. func (this *Vect) relative(other Vect) {
  56. this.posX -= other.posX
  57. this.posY -= other.posY
  58. }
  59. func dumpList(l list.List) {
  60. for e := l.Front(); e != nil; e = e.Next() {
  61. fmt.Println(e.Value.(Vect))
  62. }
  63. }
  64. func main() {
  65. coords := Vect{}
  66. reader := bufio.NewReader(os.Stdin)
  67. var visited list.List
  68. var visitedTwice Vect
  69. var hasVisitedTwice bool = false
  70. for {
  71. read, err := reader.ReadString(',')
  72. read = strings.Trim(read, ", \n")
  73. stepCount, _ := strconv.Atoi(read[1:])
  74. coords.addStep(read[:1])
  75. for i := 0; i < stepCount; i++ {
  76. if !hasVisitedTwice {
  77. if coords.inList(visited) {
  78. visitedTwice = coords
  79. hasVisitedTwice = true
  80. } else {
  81. visited.PushBack(Vect(coords))
  82. }
  83. }
  84. coords.addStepCount()
  85. }
  86. if err != nil {
  87. break
  88. }
  89. }
  90. fmt.Println(coords.toTaxiCab())
  91. if (hasVisitedTwice) {
  92. fmt.Println(visitedTwice.toTaxiCab())
  93. }
  94. }