4 ms·
That's almost identical to what I came up with, but yours is better...I didn't know about the mapValues function. def mostCommon(str: String, num: Int) = { s
by rybosome 13y ago
That's almost identical to what I came up with, but yours is better...I didn't know about the mapValues function.
def mostCommon(str: String, num: Int) = {
str.split(" ").groupBy { s => s}
.map { case (k,v) => k -> v.length }.toList
.sortBy { _._2 }.reverse.take(num).map { _._1 }
}
- haakon 13y agoThat works as well. On the other hand, I'm not a fan of these huge one-liners (including the one I posted). I split mine up a bit and posted it here: https://coderwall.com/p/ha-c2w https://coderwall.com/p/ha-c2w