27 lines
849 B
Kotlin
27 lines
849 B
Kotlin
package moe.kageru.spektacles
|
|
|
|
open class Counter<T>(source: Iterable<T>) : Iterable<Map.Entry<T, Int>> {
|
|
val counts: Map<T, Int> = mutableMapOf<T, Int>().apply {
|
|
for (element in source) {
|
|
this[element] = this.getOrDefault(element, 0) + 1
|
|
}
|
|
}
|
|
|
|
override fun iterator(): Iterator<Map.Entry<T, Int>> {
|
|
return counts.entries.iterator()
|
|
}
|
|
|
|
override fun toString(): String {
|
|
return counts.entries.joinToString("\n") { "${it.key}: ${it.value}" }
|
|
}
|
|
}
|
|
|
|
class SortedCounter<T: Comparable<T>>(source: Iterable<T>): Counter<T>(source) {
|
|
override fun toString(): String {
|
|
return counts.entries.sortedBy { it.key }.joinToString("\n") { "${it.key}: ${it.value}" }
|
|
}
|
|
}
|
|
|
|
fun <T> Iterable<T>.toCounter(): Counter<T> = Counter(this)
|
|
fun <T: Comparable<T>> Iterable<T>.toSortedCounter(): SortedCounter<T> = SortedCounter(this)
|