-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day8.kt
78 lines (69 loc) · 1.93 KB
/
Day8.kt
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
package aoc2023.day08
import util.lcm
fun parse(lines: List<String>): Network {
val input = lines[0]
val nodes = mutableMapOf<String, Node>()
(2 until lines.size).forEach { i ->
val split = lines[i].split(" = ")
val directions = split[1]
.replace("(", "")
.replace(")", "")
.trim()
.split(", ")
nodes[split[0]] = Node(directions[0], directions[1])
}
return Network(input, nodes)
}
fun part1(network: Network): Int {
var count = 0
var zzzWasReached = false
var current = "AAA"
var i = 0
while (!zzzWasReached) {
if (i == network.input.length) {
i = 0
}
val direction = network.input[i]
current = if (direction == 'L') {
network.nodes[current]!!.left
} else {
network.nodes[current]!!.right
}
count++
i++
if (current == "ZZZ") {
zzzWasReached = true
}
}
return count
}
fun part2(network: Network): Long {
val nodesEndingWithA = network.nodes.keys.filter { it.endsWith("A") }
val map = mutableMapOf<String, Long>()
nodesEndingWithA.forEach {
var zWasReached = false
var count = 0L
var i = 0
var current = it
while (!zWasReached) {
if (i == network.input.length) {
i = 0
}
val direction = network.input[i]
current = if (direction == 'L') {
network.nodes[current]!!.left
} else {
network.nodes[current]!!.right
}
count++
i++
if (current[2] == 'Z') {
zWasReached = true
}
}
map[it] = count
}
return map.values.reduce { acc, num -> lcm(acc, num) }
}
data class Network(val input: String, val nodes: Map<String, Node>)
data class Node(val left: String, val right: String)