-vpjrw
Last Updated: February 25, 2016
·
5.065K
· lukasz-madon
B2bc42f69510d6a1d2c9cde1c2214d24

Count number of words in a string (Scala)

This is improved snippet from Programming in Scala

def countWords(text: String) = {
    val counts = mutable.Map.empty[String, Int].withDefaultValue(0)
    for (rawWord <- text.split("[ ,!.]+")) {
         val word = rawWord.toLowerCase
            counts(word) += 1
    }
   counts
}

Returns Map form word to number of occurrences

Say Thanks
Respond

4 Responses
Add your response

7234
E1fc44f62e3086743c1c8a19f2b9e6a6

Another implementation, perhaps more idiomatic Scala:

def countWords(text: String) = text.split("[ ,!.]+").map(_.toLowerCase).groupBy(identity).mapValues(_.size)
over 1 year ago ·
7235
B2bc42f69510d6a1d2c9cde1c2214d24

It is more idiomatic, but it's nlog(n)

over 1 year ago ·
14795
7aca744cbe88a7b1f6bcdd1a64217724

why it's not nlog(n) and why the first one is?

over 1 year ago ·
16258
B2bc42f69510d6a1d2c9cde1c2214d24

@naderghanbari

First one is O(n) with O(n) memory. You iterate the collection once and store words in Map.

Second one is O(nlgn), because you sort the collection.

over 1 year ago ·