Created
December 12, 2017 11:27
-
-
Save tocttou/a11a6397b153911d39cf4230d7ffabeb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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