From 3550f6591408dc78a4ba9eaaf7bbc3bb2ceae611 Mon Sep 17 00:00:00 2001 From: Hubert Van De Walle Date: Wed, 15 Dec 2021 00:51:15 +0100 Subject: [PATCH] Create Counter class --- 2021/src/main/kotlin/Counter.kt | 29 +++++++++++++++++++++++++++++ 2021/src/main/kotlin/Day14.kt | 23 +++++++++-------------- 2 files changed, 38 insertions(+), 14 deletions(-) create mode 100644 2021/src/main/kotlin/Counter.kt diff --git a/2021/src/main/kotlin/Counter.kt b/2021/src/main/kotlin/Counter.kt new file mode 100644 index 0000000..e5e4335 --- /dev/null +++ b/2021/src/main/kotlin/Counter.kt @@ -0,0 +1,29 @@ +package be.vandewalleh.aoc.days + +class Counter : Iterable> { + private val map = HashMap() + 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 Counter.Companion.invoke(items: Iterable) = Counter().apply { items.forEach { this[it] += 1 } } diff --git a/2021/src/main/kotlin/Day14.kt b/2021/src/main/kotlin/Day14.kt index 3f00a39..133f971 100644 --- a/2021/src/main/kotlin/Day14.kt +++ b/2021/src/main/kotlin/Day14.kt @@ -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 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 } + 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)