From 20f20a31799c54953ec516a8e13905e633d1ae97 Mon Sep 17 00:00:00 2001 From: Hubert Van De Walle Date: Tue, 14 Dec 2021 22:57:05 +0100 Subject: [PATCH] Clean day14 --- 2021/src/main/kotlin/Day14.kt | 16 +++++++++------- 1 file changed, 9 insertions(+), 7 deletions(-) diff --git a/2021/src/main/kotlin/Day14.kt b/2021/src/main/kotlin/Day14.kt index e877104..3f00a39 100644 --- a/2021/src/main/kotlin/Day14.kt +++ b/2021/src/main/kotlin/Day14.kt @@ -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 Map.toLong() = mapValues { it.value.toLong() }.toMutableMap() + fun Grouping.toCounter() = eachCount().mapValues { it.value.toLong() }.toMutableMap() + fun MutableMap.inc(key: K, count: Long) = compute(key) { _, old -> (old ?: 0) + count } + fun MutableMap.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 }