Browse Source

Day 6

master
Chris Smith 4 years ago
parent
commit
a0e900b43f
Signed by: Chris Smith <chris@chameth.com> GPG Key ID: 3A2D4BBDC4A3C9A9
3 changed files with 1541 additions and 0 deletions
  1. 2
    0
      06/answers.txt
  2. 1477
    0
      06/input.txt
  3. 62
    0
      06/main.go

+ 2
- 0
06/answers.txt View File

@@ -0,0 +1,2 @@
1
+227612
2
+454

+ 1477
- 0
06/input.txt
File diff suppressed because it is too large
View File


+ 62
- 0
06/main.go View File

@@ -0,0 +1,62 @@
1
+package main
2
+
3
+import (
4
+	"fmt"
5
+	"github.com/csmith/aoc-2019/common"
6
+)
7
+
8
+func countOrbits(satellites map[string][]string, start string, depth int) (res int) {
9
+	for _, satellite := range satellites[start] {
10
+		res += depth + 1 + countOrbits(satellites, satellite, depth+1)
11
+	}
12
+	return
13
+}
14
+
15
+func routeToCenter(orbits map[string]string, start string) (res []string) {
16
+	next := start
17
+	for next != "COM" {
18
+		next = orbits[next]
19
+		res = append(res, next)
20
+	}
21
+	return
22
+}
23
+
24
+func countToCenter(orbits map[string]string, start string) (res map[string]int) {
25
+	res = make(map[string]int)
26
+
27
+	steps := 0
28
+	next := start
29
+	for next != "COM" {
30
+		next = orbits[next]
31
+		res[next] = steps
32
+		steps++
33
+	}
34
+	return
35
+}
36
+
37
+func shortestPath(orbits map[string]string, from, to string) int {
38
+	route := routeToCenter(orbits, from)
39
+	steps := countToCenter(orbits, to)
40
+
41
+	for i, body := range route {
42
+		if count, ok := steps[body]; ok {
43
+			return count + i
44
+		}
45
+	}
46
+	panic(fmt.Sprintf("No path found between %s and %s.", from, to))
47
+}
48
+
49
+func main() {
50
+	lines := common.ReadFileAsStrings("06/input.txt")
51
+	satellites := make(map[string][]string, len(lines))
52
+	orbits := make(map[string]string, len(lines))
53
+	for _, line := range lines {
54
+		around := line[0:3]
55
+		body := line[4:7]
56
+		satellites[around] = append(satellites[around], body)
57
+		orbits[body] = around
58
+	}
59
+
60
+	println(countOrbits(satellites, "COM", 0))
61
+	println(shortestPath(orbits, "YOU", "SAN"))
62
+}

Loading…
Cancel
Save