-
Notifications
You must be signed in to change notification settings - Fork 0
/
Day08.kt
45 lines (37 loc) · 1.16 KB
/
Day08.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
package io.dmitrijs.aoc2023
class Day08(input: List<String>) {
private val moves = input.first()
private val jumps = buildMap {
input.drop(2).onEach { line ->
line.trimEnd(')')
.split(" = (", ", ")
.let { (k, l, r) -> put(k, l to r) }
}
}
fun puzzle1(): Int {
var steps = 0
var phase = "AAA"
do {
phase = phase.jump(moves[steps++ % moves.length])
} while (phase != "ZZZ")
return steps
}
fun puzzle2(): Long {
var steps = 0
val phase = jumps.keys.filter { it.endsWith('A') }.toMutableList()
val stops = IntArray(phase.size)
do {
val dir = moves[steps++ % moves.length]
phase.indices.forEach { i ->
phase[i] = phase[i].jump(dir)
if (stops[i] == 0 && phase[i].endsWith("Z")) stops[i] = steps
}
} while (stops.any { it == 0 })
return lcm(stops.map { it.toLong() })
}
private fun String.jump(direction: Char) = if (direction == 'L') {
jumps.getValue(this).first
} else {
jumps.getValue(this).second
}
}