-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathday3.go
More file actions
127 lines (116 loc) · 2.28 KB
/
Copy pathday3.go
File metadata and controls
127 lines (116 loc) · 2.28 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
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
package main
import (
"fmt"
"io/ioutil"
"log"
"math"
"os"
"strings"
)
type vec struct {
dir rune
dist int
}
type coord struct {
x, y int
}
func readVecPaths(filePath string) [][]vec {
txt, err := ioutil.ReadFile(filePath)
if err != nil {
log.Fatal(err)
}
lines := strings.TrimSpace(string(txt))
var vecPaths [][]vec
for _, line := range strings.Split(lines, "\n") {
var vecPath []vec
for _, tok := range strings.Split(line, ",") {
var v vec
_, err := fmt.Sscanf(tok, "%c%d", &v.dir, &v.dist)
if err != nil {
log.Fatalf("failed to parse vec: %s", tok)
}
vecPath = append(vecPath, v)
}
vecPaths = append(vecPaths, vecPath)
}
return vecPaths
}
func toPath(vecPath []vec) []coord {
var path []coord
var cur coord
for _, v := range vecPath {
var dim *int
d := 0
switch v.dir {
case 'U':
dim = &cur.y
d = +1
case 'D':
dim = &cur.y
d = -1
case 'R':
dim = &cur.x
d = +1
case 'L':
dim = &cur.x
d = -1
default:
log.Fatalf("bad direction: %s", v.dir)
}
for n := v.dist; n > 0; n-- {
*dim += d
path = append(path, cur)
}
}
return path
}
func findIntersects(coords1, coords2 []coord) []coord {
coords := make(map[coord]bool)
for _, c := range coords1 {
coords[c] = true
}
var intersections []coord
for _, c := range coords2 {
if coords[c] {
intersections = append(intersections, c)
}
}
return intersections
}
func dist(c coord) int {
return int(math.Abs(float64(c.x)) + math.Abs(float64(c.y)))
}
func closestIntersect(intersects []coord) int {
var closestDist int
for _, coord := range intersects {
if d := dist(coord); closestDist == 0 || d < closestDist {
closestDist = d
}
}
return closestDist
}
func stepsTo(to coord, path []coord) int {
for i, cur := range path {
if cur == to {
return i + 1
}
}
return 0
}
func fastestIntersect(coords []coord, path1, path2 []coord) int {
var speed int
for _, c := range coords {
sum := stepsTo(c, path1) + stepsTo(c, path2)
if speed == 0 || sum < speed {
speed = sum
}
}
return speed
}
func main() {
vecPaths := readVecPaths(os.Args[1])
path1, path2 := toPath(vecPaths[0]), toPath(vecPaths[1])
intersects := findIntersects(path1, path2)
fmt.Println(closestIntersect(intersects))
fmt.Println(fastestIntersect(intersects, path1, path2))
}