1
0

Create Counter class

This commit is contained in:
Hubert Van De Walle 2021-12-15 00:51:15 +01:00
parent 20f20a3179
commit 3550f65914
2 changed files with 38 additions and 14 deletions

View File

@ -0,0 +1,29 @@
package be.vandewalleh.aoc.days
class Counter<K> : Iterable<Map.Entry<K, Long>> {
private val map = HashMap<K, Long>()
operator fun get(key: K) = map[key] ?: 0L
operator fun set(key: K, count: Long) {
map[key] = count
}
operator fun set(key: K, count: Int) {
if (count == 0)
map.remove(key)
else
map[key] = count.toLong()
}
fun toMap() = map.toMap(HashMap())
override fun toString() = map.toString()
fun minValue() = map.minOf { it.value }
fun maxValue() = map.maxOf { it.value }
override fun iterator() = toMap().iterator()
companion object
}
operator fun <T> Counter.Companion.invoke(items: Iterable<T>) = Counter<T>().apply { items.forEach { this[it] += 1 } }

View File

@ -12,25 +12,20 @@ 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 <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 }
val polymer = Counter(template.windowed(2)) // {NN=1, NC=1, CB=1}
val counts = Counter(template.toCharArray().toList()) // {N=2, C=1, ...}
// {NN=1, NC=1, CB=1}
val polymer = template.windowed(2).groupingBy { it }.toCounter()
// {N=2, C=1, ...}
val counts = template.groupingBy { it }.toCounter()
repeat(step) {
polymer.toMap().forEach { (pair, value) ->
polymer.forEach { (pair, value) ->
val (left, right) = pairs[pair]!!
polymer.dec(pair, value)
polymer.inc(left, value)
polymer.inc(right, value)
counts.inc(left[1], value)
polymer[pair] -= value
polymer[left] += value
polymer[right] += value
counts[left[1]] += value
}
}
return counts.maxOf { it.value } - counts.minOf { it.value }
return counts.maxValue() - counts.minValue()
}
override fun part1() = run(10)