-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday09.go
138 lines (101 loc) Β· 2.38 KB
/
day09.go
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
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
package day09
import (
"fmt"
"math"
"strconv"
"strings"
)
type Instruction struct {
direction string
steps int
}
func parseInstructions(input string) (instructions []Instruction) {
rawInstructions := strings.Split(input, "\n")
for _, rawInstruction := range rawInstructions {
instructionParts := strings.Split(rawInstruction, " ")
numericSteps, err := strconv.Atoi(instructionParts[1])
if err != nil {
panic("Error converting steps to int")
}
instructions = append(instructions, Instruction{instructionParts[0], numericSteps})
}
return
}
func getDistance(head Knot, tail Knot) int {
dx := head.x - tail.x
dy := head.y - tail.y
distance := math.Sqrt(math.Pow(float64(dx), 2) + math.Pow(float64(dy), 2))
return int(math.Round(distance))
}
type Knot struct {
x int
y int
}
func (knot *Knot) moveOne(direction string) {
switch direction {
case "U":
knot.y++
case "D":
knot.y--
case "L":
knot.x--
case "R":
knot.x++
}
}
func (tail *Knot) followHead(head *Knot) {
if getDistance(*head, *tail) < 2 {
return
}
if head.y > tail.y {
tail.moveOne("U")
} else if head.y < tail.y {
tail.moveOne("D")
}
if head.x > tail.x {
tail.moveOne("R")
} else if head.x < tail.x {
tail.moveOne("L")
}
}
func part1(input string) int {
instructions := parseInstructions(input)
head := Knot{}
tail := Knot{}
tailPositions := make(map[string]bool, 0)
for _, instruction := range instructions {
for s := 0; s < instruction.steps; s++ {
head.moveOne(instruction.direction)
tail.followHead(&head)
tailPosition := fmt.Sprintf("%d-%d", tail.x, tail.y)
tailPositions[tailPosition] = true
}
}
return len(tailPositions)
}
const NUMBER_OF_TAILS = 9
func part2(input string) int {
instructions := parseInstructions(input)
head := Knot{}
var tails [NUMBER_OF_TAILS]Knot
tailPositions := make(map[string]bool, 0)
for _, instruction := range instructions {
for s := 0; s < instruction.steps; s++ {
head.moveOne(instruction.direction)
for tailIndex := range tails {
var tailHead *Knot
if tailIndex == 0 {
tailHead = &head
} else {
tailHead = &tails[tailIndex-1]
}
tails[tailIndex].followHead(tailHead)
if tailIndex+1 == NUMBER_OF_TAILS {
tailPosition := fmt.Sprintf("%d-%d", tails[tailIndex].x, tails[tailIndex].y)
tailPositions[tailPosition] = true
}
}
}
}
return len(tailPositions)
}