-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
129 lines (112 loc) · 1.7 KB
/
main.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
package main
import (
input "aoc2020/inpututils"
"fmt"
"strconv"
)
func main() {
fmt.Println("--- Part One ---")
fmt.Println(Part1("input.txt"))
fmt.Println("--- Part Two ---")
fmt.Println(Part2("input.txt"))
}
func Part1(filename string) int {
lines := input.ReadLines(filename)
direction, x, y := 90, 0, 0
for _, l := range lines {
d, v := string(l[0]), toInt(l[1:])
if d == "R" {
direction = (direction + v) % 360
}
if d == "L" {
// add 360 to stop becoming negative
direction = (direction + 360 - v) % 360
}
if d == "N" {
y += v
}
if d == "E" {
x += v
}
if d == "S" {
y -= v
}
if d == "W" {
x -= v
}
if d == "F" {
if direction == 90 {
x += v
}
if direction == 180 {
y -= v
}
if direction == 270 {
x -= v
}
if direction == 0 {
y += v
}
}
}
return abs(x) + abs(y)
}
func Part2(filename string) int {
lines := input.ReadLines(filename)
wx, wy := 10, 1
sx, sy := 0, 0
for _, l := range lines {
d, v := string(l[0]), toInt(l[1:])
if d == "R" {
wx, wy = rotateCoords(wx, wy, v)
}
if d == "L" {
wx, wy = rotateCoords(wx, wy, 360-v)
}
if d == "N" {
wy += v
}
if d == "E" {
wx += v
}
if d == "S" {
wy -= v
}
if d == "W" {
wx -= v
}
if d == "F" {
sx += wx * v
sy += wy * v
}
}
return abs(sx) + abs(sy)
}
func rotateCoords(x, y, r int) (int, int) {
if r == 90 {
return y, -x
}
if r == 180 {
return -x, -y
}
if r == 270 {
return -y, x
}
return x, y
}
func abs(x int) int {
if x >= 0 {
return x
}
return -1 * x
}
func check(err error) {
if err != nil {
panic(err)
}
}
func toInt(s string) int {
i, err := strconv.Atoi(s)
check(err)
return i
}