Skip to content

Instantly share code, notes, and snippets.

@kevin-lee
Last active January 15, 2016 12:16
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save kevin-lee/fbc3285531ad677acd4c to your computer and use it in GitHub Desktop.
Word Count Code Examples
/**
* @author Kevin Lee
* @since 2016-01-15
*/
object WordCount extends App {
def wordCount(lines: String): Map[String, Array[Int]] =
lines.split('\n')
.map(_.trim)
.map(_.split("[\\s]+"))
.zipWithIndex
.flatMap {
case (words, index) => words.map((_, index + 1))
}
.groupBy {
case (word, _) => word
}
.mapValues(
_.map {
case (word, lineNumber) => lineNumber
} distinct
)
def wordCount2(lines: String): Map[String, Array[Int]] =
(for {
(line, index) <- lines.split('\n').zipWithIndex
words = line.trim.split("[\\s]+")
word <- words
lineNumber = index + 1
} yield (word, lineNumber))
.groupBy {
case (word, _) => word
}
.mapValues(
_.map {
case (_, lineNumber) => lineNumber
} distinct
)
case class WordLine(word: String, lineNumber: Int)
def wordCount3(lines: String): Map[String, Array[Int]] = {
val wordsAndLines = for {
(line, index) <- lines.split('\n').zipWithIndex
words = line.trim.split("[\\s]+")
word <- words
lineNumber = index + 1
} yield WordLine(word, lineNumber)
wordsAndLines.groupBy(_.word)
.mapValues(_.map(_.lineNumber).distinct)
}
val foo =
"""World of Warcraft
|Hello World
|Hello Hello""".stripMargin
List(wordCount(foo), wordCount2(foo), wordCount3(foo))
.foreach { result =>
result.foreach {
case (word, lineNumbers) =>
println(s"$word : ${lineNumbers.mkString(" ")}")
}
println("-------------------------------------")
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment