1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
|
package main
import (
"bufio"
"fmt"
"log"
"os"
"regexp"
"strconv"
)
type head struct {
x, y int
knot *knot
}
func (h *head) move(direction byte, count int) *knot {
switch direction {
case 'U':
h.y += count
case 'R':
h.x += count
case 'D':
h.y -= count
case 'L':
h.x -= count
}
return h.knot
}
type knot struct {
x, y int
knot *knot
visited map[struct{ x, y int }]bool
}
func (t *knot) simulate(hx, hy int) (*knot, int, int) {
xd := (hx - t.x)
yd := (hy - t.y)
s := func() int {
return yd*yd + xd*xd
}
if s() > 2 {
t.move(xd, yd)
c := struct{ x, y int }{t.x, t.y}
if t.visited != nil {
_, ok := t.visited[c]
if !ok {
t.visited[c] = true
}
}
}
return t.knot, t.x, t.y
}
func (t *knot) move(xd, yd int) {
if xd*xd > 0 {
if xd > 0 {
t.x += 1
} else {
t.x -= 1
}
}
if yd*yd > 0 {
if yd > 0 {
t.y += 1
} else {
t.y -= 1
}
}
}
func NewRope(length int) (*head, *knot) {
k := &knot{0, 0, nil, make(map[struct{ x, y int }]bool)}
t := k
for i := 0; i < length-2; i++ {
k = &knot{0, 0, k, nil}
}
return &head{
0, 0, k,
}, t
}
func main() {
f, err := os.Open("day9.txt")
if err != nil {
fmt.Println("Could not find input file")
}
h, t := NewRope(10)
s := bufio.NewScanner(f)
for s.Scan() {
r := regexp.MustCompile(`(\w+) (\d+)`)
m := r.FindSubmatch(s.Bytes())
direction := m[1][0]
count, err := strconv.Atoi(string(m[2]))
if err != nil {
log.Fatal("Invalid number string")
}
for i := 0; i < count; i++ {
k := h.move(direction, 1)
x, y := h.x, h.y
for k != nil {
k, x, y = k.simulate(x, y)
}
}
}
fmt.Println(len(t.visited) + 1)
}
|