-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathd9p2.go
More file actions
75 lines (69 loc) · 1.15 KB
/
d9p2.go
File metadata and controls
75 lines (69 loc) · 1.15 KB
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
package main
import (
"io"
"math"
"os"
"strconv"
"strings"
)
type Point struct {
X, Y int
}
func main() {
f, _ := os.Open("input.txt")
b, _ := io.ReadAll(f)
s := string(b)
rope := make([]*Point, 10)
for i := 0; i < 10; i++ {
rope[i] = &Point{0, 0}
}
tail := rope[9]
head := rope[0]
visited := make(map[Point]bool)
visited[*tail] = true
for _, line := range strings.Split(s, "\n") {
if line == "" {
continue
}
split := strings.Split(line, " ")
times, _ := strconv.Atoi(split[1])
movement := split[0]
for i := 0; i < times; i++ {
switch movement {
case "U":
head.X--
case "D":
head.X++
case "L":
head.Y--
case "R":
head.Y++
}
for i := 1; i < 10; i++ {
prev := rope[i-1]
act := rope[i]
if math.Abs(float64(act.X)-float64(prev.X)) <= 1 && math.Abs(float64(act.Y)-float64(prev.Y)) <= 1 {
break
}
if prev.Y < act.Y {
act.Y--
} else if prev.Y > act.Y {
act.Y++
}
if prev.X < act.X {
act.X--
} else if prev.X > act.X {
act.X++
}
}
visited[*tail] = true
}
}
r := 0
for _, v := range visited {
if v {
r++
}
}
println(r)
}