4 ms·
Since we're already on the JVM, here's my solution for Scala: def top10(s: String) = s.split(' ').groupBy(identity).mapValues(_.size).toList.sortBy(-_._2).take
by haakon 13y ago
Since we're already on the JVM, here's my solution for Scala:
def top10(s: String) = s.split(' ').groupBy(identity).mapValues(_.size).toList.sortBy(-_._2).take(10).map(_._1)
- rybosome 13y agoThat'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