1. Keeping counts of things as mutable state. `Mu...
# advent-of-code
n
2. Keeping counts of things as mutable state.
MutableMap<T, Long>
is okay-ish for this, but incrementing feels very awkward
Copy code
myCounts[something] = myCounts.getOrDefault(something, 0) + numberFound
I've generally found that updating state in maps can be a bit annoying so I do have a general helper function (which I think would be worth having in stdlib tbh)
Copy code
fun <K, V> MutableMap<K, V>.update(k: K, transform: (V?) -> V) = set(k, transform(get(k)))
So it becomes
Copy code
myCounts.update(k) { (it ?: 0) + numberFound
But still, end up repeating quite a bit. If there isn't a better way then I may just have a dedicated Counter (a la python) and possibly deal with both things with one stone
🙏 1
e
if I had to do it a lot, I'd probably write
Copy code
class MutableLong(var value: Long)
val myCounts = mutableMapOf<T, MutableLong>()
myCounts.getOrPut(k) { MutableLong(0) }.value += number
as that also avoids repeatedly boxing Long
👍 1
but so far in AoC I've usually just restructured the program to use LongArray which ends up both shorter and faster
l
On JVM with Java 1.8+, your
update
fonction is basically the
MutableMap.compute
function ignoring the first argument of the lambda. You can use
map.compute(key) { _, value -> (value ?: 0) + numberFound }
. You also have a
computeIfPresent
and
computeIfAbsent
n
yeah but this is basically Java internals at this point no
it's not part of the Kotlin language. But if the underlying data structure already provides that operation, all the more reason to provide something like it.
e
kotlin-stdlib is still Java 1.6+ though
even if you added it to kotlin-stdlib-jdk8, that still excludes common (js and native)… or if you put it in common, that breaks jdk6/7…