Answer on Question#45830 - Programming - Other
Question
What is the best data structure to solve this problem? (I will use Scala)
Your job is to read an arbitrary number of words from the standard input and keep track how many times each word occurs in the input. After the end of the input is reached, print how many times each unique word has occurred (in no particular word order or numerical order
Answer
The most appropriate data structure to implement solution for this task is dictionary (it is a kind of associative array), it contains a set of pairs - (key, value). In your case, key is a word from input stream, value - number of occurrences of this word. In Scala it's called Map. You have to iterate over your text and increment value of each word you find in the text.
val wordCounts = scala.collection.mutable.Map[String, Int]()
// Read words from standard input
Iterator.continually(io.StdIn.readLine()).takeWhile(_ != null).foreach { line =>
line.split("\\s+").foreach { word =>
wordCounts(word) = wordCounts.getOrElse(word, 0) + 1
}
}
// Print the word counts
wordCounts.foreach { case (word, count) =>
println(s"$word: $count")
}