fun subgroups(data: Map<Int, String>): Map<String, List<Int>> {
if (data.isEmpty()) throw IllegalArgumentException()
val counter = data.values.toSet().associateWithTo(mutableMapOf()){ 1 }
var last = data.values.first()
val result = mutableMapOf<String, List<Int>>()
data.forEach { k, v ->
if (v != last) {
counter[last] = counter.getOrDefault(last, 0) + 1
last = v
}
"$v${counter[v]}".let { key ->
result[key] = result.getOrDefault(key, listOf()) + k
}
}
return result
}
val result = input
.fold(
mutableListOf<Pair<String, MutableList<Int>>>() to mutableMapOf<String, Int>()
) { acc, pair ->
val result = acc.first
val counters = acc.second
val number = pair.first
val letter = pair.second
if (result.lastOrNull()?.first == letter + counters[letter]) {
result.last().second.add(number)
} else {
result.add(letter + (counters.getOrElse(letter) { 0 } + 1).also { counters[letter] = it } to mutableListOf(number))
}
acc
}
.first
.toMap()
3条答案
按热度按时间4ktjp1zp1#
给定
Pair<Int, String>
的List
(因为顺序很重要),如下所示:你可以这样做:
最后,当你需要将这个
[(1,a1),(2,a1),(3,b1),(4,b1),(5,b1),(6,a2),(7,a2),(8,a2)]
变成这样:
{a1=[1,2],bl =[3,4,5],a2=[6,7,8]}
如果你碰巧有一个
Map<Int, String>
,你可以在把它传递给groupCount
之前调用toList()
。8e2ybdfx2#
我想这是一个非常特殊的用例。一个不太实用的实现可能看起来像这样:
希望这对你有用
xytpbqjk3#