Skip to content

Instantly share code, notes, and snippets.

@tocttou
Created December 12, 2017 11:27
Show Gist options
  • Save tocttou/a11a6397b153911d39cf4230d7ffabeb to your computer and use it in GitHub Desktop.
Save tocttou/a11a6397b153911d39cf4230d7ffabeb to your computer and use it in GitHub Desktop.
package utils
class FrequencyMap<K, Int>(private val b: MutableMap<K, kotlin.Int>)
: MutableMap<K, kotlin.Int> by b {
fun add(key: K, freq: kotlin.Int = 1) {
b.computeIfPresent(key) { _, b -> b + freq }
b.putIfAbsent(key, freq)
}
fun add(vararg pairs: Pair<K, kotlin.Int>) {
for (pair in pairs) {
val (key, freq) = pair
add(key, freq)
}
}
fun removeFreq(key: K, freq: kotlin.Int = 1) {
if (b.get(key) == null || freq < 1) return
else if (b.get(key)!! - freq < 1) b.remove(key)
b.computeIfPresent(key) { _, b -> b - freq }
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment