Question

Scala: Write and test a Program as elegantly as possible Given a piece of text, create...

Scala: Write and test a Program as elegantly as possible

Given a piece of text, create a histogram of letter pairs (order from high to low). For instance, for the text, “this is a good thing”,

the letter pairs are: th, hi, is, is, go, oo, od, th, hi, in, and ng. (ignore a) The histogram will be:
th: 2, is: 2, hi: 2 go: 1, oo: 1, od: 1, in: 1, ng: 1

Sample Input/Output:

Enter text: this is a good thing
Histogram: th: 2, is: 2, hi: 2 go: 1, oo: 1, od: 1, in: 1, ng: 1
Enter text: coooooool
Histogram: oo: 6, co: 1, ol: 1
0 0
Add a comment Improve this question Transcribed image text
Answer #1

Code in Scala:

import scala.collection.immutable.ListMap //immutable listmap cannot be updated
import scala.collection.mutable.Map //mutable map can be updated

object Histogram {

  def main(args: Array[String]): Unit =
  {
    println("Enter text: ") //Print message
    val string = scala.io.StdIn.readLine().toLowerCase //Take input from user and process it to lower case
    var word_list: List[String] = string.split("\\s+").toList //Split given string by white spaces e.g. To do => ['To', 'do']
    word_list = word_list.filter(_.length > 1) //Eliminate words with character length = 1
    val map:Map[String, Int] = Map() //Create a map with key as String and value as Integer
    for(word <- word_list) //Iterate over list of words
      {
        for(character_index <- 1 until word.length) //Iterate over each word
          {
            val key = word.charAt(character_index - 1).toString + word.charAt(character_index) //Take two characters from string and concatenate them
            map(key) = if(map.contains(key)) map(key) + 1 else 1 //If key exists, increment current count otherwise create entry
          }
      }

    val sorted_map = ListMap(map.toSeq.sortWith(_._2 > _._2):_*) //Sort map according to values in descending order
    print("Histogram:\t") //Display message
    for((key, value) <- sorted_map) //Iterate over sorted map
    {
      print(key+":"+value+"\t") //Print key:value pair
    }
  }
}

Code Description:
Input: String
Output: List of substrings with frequency count

Main Logic:

Input: This is a good thing

Execution:

  1. Take input string from user (This is a good thing)
  2. Convert the string to lowercase (this is a good thing)
  3. Split the string according to one or more (\\s+) white spaces (['this', 'is', 'a', 'good', 'thing'])
  4. Remove strings with length 1 (['this', 'is', 'good', 'thing'])
  5. Initialize a map to store substrings and their counts
  6. Iterate over list created from Step 4 (['this', 'is', 'good', 'thing'])
    1. ​​​​​​​Iterate over each character of current string (['t', 'h', 'i', 's'])
      • Concatenate neighboring characters and create substrings (['th', 'hi', 'is'])
      • Check whether substring is present in map otherwise create an entry
        • If substring is present, increment the existing count by 1
  7. Sort items of map according to values from (key, value) pair and follow descending order
  8. Iterate over sorted map and print substring and frequency count
Add a comment
Know the answer?
Add Answer to:
Scala: Write and test a Program as elegantly as possible Given a piece of text, create...
Your Answer:

Post as a guest

Your Name:

What's your source?

Earn Coins

Coins can be redeemed for fabulous gifts.

Not the answer you're looking for? Ask your own homework help question. Our experts will answer your question WITHIN MINUTES for Free.
Similar Homework Help Questions
  • Scala: Write a Program as elegantly as possible Given a piece of text, create a histogram...

    Scala: Write a Program as elegantly as possible Given a piece of text, create a histogram of letter pairs (order from high to low). For instance, for the text, “this is a good thing”, the letter pairs are: th, hi, is, is, go, oo, od, th, hi, in, and ng. (ignore a) The histogram will be: th: 2, is: 2, hi: 2 go: 1, oo: 1, od: 1, in: 1, ng: 1 Sample Input/Output: Enter text: this is a good...

  • Write a program named text_indexing.c that does the following: Reads text and stores it as one...

    Write a program named text_indexing.c that does the following: Reads text and stores it as one string called text. You can read from a file or from the user. (In my implementation, I read only one paragraph (up to new line) from the user. With this same code, I am able to read data from a file by using input redirection (executable < filename) when I run the program. See sample runs below). You can assume that the text will...

  • Question 1 CSEB113 Write a program to create customer's bll for an electrical appliance company. Assume...

    Question 1 CSEB113 Write a program to create customer's bll for an electrical appliance company. Assume the company sells only three different products: TV, VCR and CD player. The unit prices are RM3000, RM500 and RM300 respectively. The program must read the quantity of each piece of the items purchased from the user. It then calculates the cost of each item, the subtotal and the total cost after an 6% of GST. Your program must use the following functions, given...

  • Write a complete C program that inputs a paragraph of text and prints out each unique...

    Write a complete C program that inputs a paragraph of text and prints out each unique letter found in the text along with the number of times it occurred. A sample run of the program is given below. You should input your text from a data file specified on the command line. Your output should be formatted and presented exactly like the sample run (i.e. alphabetized with the exact spacings and output labels). The name of your data file along...

  • Please Code in Java and follow the directions given Thanks Program required Directions .A palindrome is a str...

    Please Code in Java and follow the directions given Thanks Program required Directions .A palindrome is a string that reads the same forward and backward, i.e., the letters are the same whether you read them from right to left or from left to right. Examples: 3 a) radar à is a palindrome b)Able was I ere I saw Elba à is a palindrome e good à not a palindrome Write java program to read a line of text and tell...

  • JAVA, please You must write a robust program meaning that your program should not crash with...

    JAVA, please You must write a robust program meaning that your program should not crash with any given data. Data validation must be done any time that user enters an input. Write a program that 1. Gets an infix expression form the user and evaluate the expression using stack ADT a. Finds the postfix equivalent of the given infix expression b. Evaluate the created postfix expression. c. Note: your program should not crash when you enter an invalid expression such...

  • write a new test program called RemoveDuplicates.java. The program reads text input from keyboard or a text file and adds the words to a BST. The program then traverses the BST and prints out the word...

    write a new test program called RemoveDuplicates.java. The program reads text input from keyboard or a text file and adds the words to a BST. The program then traverses the BST and prints out the words in order (based on ASCII/UNICODE order) on the screen (or to output text file). Note that you may need to make some changes to BST.java. Sample test: ----jGRASP exec: java -ea removeDuplicates Original Text: a B 2 n w C q K l 0...

  • using java Program: Please read the complete prompt before going into coding. Write a program that...

    using java Program: Please read the complete prompt before going into coding. Write a program that handles the gradebook for the instructor. You must use a 2D array when storing the gradebook. The student ID as well as all grades should be of type int. To make the test process easy, generate the grade with random numbers. For this purpose, create a method that asks the user to enter how many students there are in the classroom. Then, in each...

  • In this lab you will write a spell check program. The program has two input files:...

    In this lab you will write a spell check program. The program has two input files: one is the dictionary (a list of valid words) and the other is the document to be spellchecked. The program will read in the words for the dictionary, then will read the document and check whether each word is found in the dictionary. If not, the user will be prompted to leave the word as is or type in a replacement word and add...

  • In c++ Write a program that allows the user to type in any one-line question and then answers tha...

    in c++ Write a program that allows the user to type in any one-line question and then answers that question. Your program won't really respond to the question, rather it will read a random response from a file. Requirements Your program should have a function called getQuestion() which prompts the user for a question and returns the number of characters in the question (including spaces and punctuation, not including the ending newline). If the user enters an empty string they...

ADVERTISEMENT
Free Homework Help App
Download From Google Play
Scan Your Homework
to Get Instant Free Answers
Need Online Homework Help?
Ask a Question
Get Answers For Free
Most questions answered within 3 hours.
ADVERTISEMENT
ADVERTISEMENT