This repository has been archived by the owner on Apr 15, 2023. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
69 lines (60 loc) · 1.45 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
package main
import (
"fmt"
"log"
"math"
"github.com/derat/advent-of-code/lib"
)
func main() {
// Part 1:
var ox, oy float64 // ship coords
var head float64 = 90 // ship heading (east)
// Part 2:
var sx, sy float64 // ship coords
var wx, wy float64 = 10, 1 // waypoint relative to ship
rotWay := func(deg float64) {
dist := math.Sqrt(math.Pow(wx, 2) + math.Pow(wy, 2))
// atan2 is needed to preserve the signs of the individual coordinates:
// when passing a ratio to atan, (10,1) and (-10,-1) are indistinguishable.
rad := math.Atan2(wx, wy) + (deg * math.Pi / 180)
wx = math.Sin(rad) * dist
wy = math.Cos(rad) * dist
}
for _, ln := range lib.InputLines("2020/12") {
var op string
var v float64
lib.Extract(ln, `^([NSEWLRF])(\d+)$`, &op, &v)
switch op {
case "N":
oy += v
wy += v
case "S":
oy -= v
wy -= v
case "E":
ox += v
wx += v
case "W":
ox -= v
wx -= v
case "L":
head = math.Mod(head-v, 360)
rotWay(-v)
case "R":
head = math.Mod(head+v, 360)
rotWay(v)
case "F":
// Overkill: input just uses intervals of 90 degrees for rotations.
rad := head * math.Pi / 180
ox += math.Sin(rad) * v
oy += math.Cos(rad) * v
sx += wx * v
sy += wy * v
default:
log.Fatalf("invalid op %q", op)
}
}
// https://en.wikipedia.org/wiki/Taxicab_geometry
fmt.Println(int(math.Round(math.Abs(ox) + math.Abs(oy))))
fmt.Println(int(math.Round(math.Abs(sx) + math.Abs(sy))))
}