1
0

Clean day14

This commit is contained in:
Hubert Van De Walle 2021-12-14 22:57:05 +01:00
parent eff95027de
commit 20f20a3179

View File

@ -12,20 +12,22 @@ class Day14 : BaseDay() {
val pairs = input.lines.value.drop(2)
.associate { it.split(" -> ").let { (a, b) -> a to (a[0] + b to b + a[1]) } }
fun <K> Map<K, Int>.toLong() = mapValues { it.value.toLong() }.toMutableMap()
fun <T, K> Grouping<T, K>.toCounter() = eachCount().mapValues { it.value.toLong() }.toMutableMap()
fun <K> MutableMap<K, Long>.inc(key: K, count: Long) = compute(key) { _, old -> (old ?: 0) + count }
fun <K> MutableMap<K, Long>.dec(key: K, count: Long) = compute(key) { _, old -> (old ?: 0) - count }
// {NN=1, NC=1, CB=1}
val polymer = template.windowed(2).groupingBy { it }.eachCount().toLong()
val polymer = template.windowed(2).groupingBy { it }.toCounter()
// {N=2, C=1, ...}
val counts = template.groupingBy { it }.eachCount().toLong()
val counts = template.groupingBy { it }.toCounter()
repeat(step) {
polymer.toMap().forEach { (pair, value) ->
val (left, right) = pairs[pair]!!
polymer[pair]?.let { old -> polymer[pair] = old - value }
polymer[left] = (polymer[left] ?: 0) + value
polymer[right] = (polymer[right] ?: 0) + value
counts[left[1]] = (counts[left[1]] ?: 0) + value
polymer.dec(pair, value)
polymer.inc(left, value)
polymer.inc(right, value)
counts.inc(left[1], value)
}
}
return counts.maxOf { it.value } - counts.minOf { it.value }