Question #45830

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

For example, if the input is

hello hello
world goodbye hello
world
then one possible output is

world 2
goodbye 1
hello 3

Expert's answer

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")
}

Need a fast expert's response?

Submit order

and get a quick answer at the best price

for any assignment or question with DETAILED EXPLANATIONS!

LATEST TUTORIALS
APPROVED BY CLIENTS