-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathy25day11.kt
More file actions
24 lines (21 loc) · 1 KB
/
Copy pathy25day11.kt
File metadata and controls
24 lines (21 loc) · 1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
import kotlin.time.measureTimedValue
fun main() {
val input = generateSequence(::readlnOrNull).toList()
val edges = input.associate { it.substringBefore(": ") to it.substringAfter(": ").split(" ") }
measureTimedValue { // part 1
val cache = HashMap<String, Long>()
fun countPaths(from: String): Long = cache.getOrPut(from) {
if (from == "out") 1 else edges[from]?.sumOf(::countPaths) ?: 0
}
countPaths("you")
}.also(::println)
measureTimedValue { // part 2
val caches = HashMap<String, HashMap<String, Long>>()
fun countPaths(from: String, to: String): Long =
caches.getOrPut(to) { HashMap<String, Long>() }.getOrPut(from) {
if (from == to) 1 else edges[from]?.sumOf { countPaths(it, to) } ?: 0
}
countPaths("svr", "fft") * countPaths("fft", "dac") * countPaths("dac", "out") +
countPaths("svr", "dac") * countPaths("dac", "fft") * countPaths("fft", "out")
}.also(::println)
}