-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathday8.go
77 lines (66 loc) · 1.73 KB
/
day8.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
package main
import (
"fmt"
"regexp"
"strings"
"github.com/Alex-Waring/AoC/utils"
)
type instruction struct {
left string
right string
}
func part1(directions string, instructions map[string]instruction, start_location string) int {
defer utils.Timer("part1")()
loops := 0
for start_location != "ZZZ" {
if directions[loops%len(directions)] == 'R' {
start_location = instructions[start_location].right
} else {
start_location = instructions[start_location].left
}
loops++
}
return loops
}
func endsWith(location string, letter string) bool {
regex := "[A-Z][A-Z]" + letter
found, _ := regexp.MatchString(regex, location)
return found
}
func main() {
lines := utils.ReadInput("input.txt")
directions := lines[0]
raw_instructions := utils.RemoveSliceSpaces(lines[1:])
instructions := map[string]instruction{}
for _, line := range raw_instructions {
key := strings.Fields(line)[0]
left := strings.TrimPrefix(strings.TrimSuffix(strings.Fields(line)[2], ","), "(")
right := strings.TrimSuffix(strings.Fields(line)[3], ")")
instructions[key] = instruction{left: left, right: right}
}
current_location := "AAA"
loops := part1(directions, instructions, current_location)
fmt.Println(loops)
defer utils.Timer("part2")()
ghost_starts := []string{}
steps := []int{}
for key, _ := range instructions {
if endsWith(key, "A") {
ghost_starts = append(ghost_starts, key)
}
}
for _, start := range ghost_starts {
loops = 0
for !endsWith(start, "Z") {
if directions[loops%len(directions)] == 'R' {
start = instructions[start].right
} else {
start = instructions[start].left
}
loops++
}
steps = append(steps, loops)
}
part2 := utils.LCM(steps[0], steps[1], steps[2:]...)
fmt.Println(part2)
}