Re:LINQ Ruined My Favorite Interview Question
by rybosome on Friday July 12, 2013 @01:56AM
(#6031164)
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 } }
That 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
def top10(s: String) = s.split(' ').groupBy(identity).mapValues(_.size).toList.sortBy(-_._2).take(10).map(_._1)