generated from devries/aoc_template
-
Notifications
You must be signed in to change notification settings - Fork 0
/
solution.go
71 lines (57 loc) · 1.29 KB
/
solution.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
package day08p2
import (
"io"
"strings"
"aoc/utils"
)
func Solve(r io.Reader) any {
lines := utils.ReadLines(r)
// Get all LR moves
moves := []rune(lines[0])
neighbors := make(map[string][]string)
for i := 2; i < len(lines); i++ {
parts := strings.Split(lines[i], " = ")
destinations := strings.Trim(parts[1], "()")
leftright := strings.Split(destinations, ", ")
neighbors[parts[0]] = leftright
}
cyclesteps := int64(1)
// Let's find the ones ending in A
for pos := range neighbors {
if !strings.HasSuffix(pos, "A") {
continue
}
var steps int64
hits := []Hit{}
outer:
for {
for _, d := range moves {
next := neighbors[pos]
steps++
switch d {
case 'L':
pos = next[0]
case 'R':
pos = next[1]
}
if strings.HasSuffix(pos, "Z") {
h := Hit{pos, steps}
for _, ph := range hits {
if h.Candidate == ph.Candidate && h.Steps == 2*ph.Steps {
// Let's check if we are getting back to the same position in regular cycles.
cyclesteps = utils.Lcm(cyclesteps, h.Steps-ph.Steps)
break outer
}
}
hits = append(hits, h)
}
}
}
}
return cyclesteps
}
// State when destination candidate is hit
type Hit struct {
Candidate string // Ends with Z
Steps int64 // step at which it was hit
}