In: Computer Science
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
Complete scala program with description in comments:
object Histogram {
def main(args: Array[String]) {
//take user input
println("Enter text:")
var input = scala.io.StdIn.readLine()
// length of the input string
var length = input.length()
var str = ""
// create an object of mutable LinkedHashMap
// key is string type, value is integer type for mainitaining
count
val histogram = scala.collection.mutable.LinkedHashMap[String,
Int]()
var index = 0
// traverse till second last character in the input string
// why second last: because we are creating histogram of
pairs.
// last pair would be second last character and last
character
for(index <- 0 to (length - 2))
{
// check if current character or next character not a white
space
// this check ignores whitespaces and single letter
if( !(input(index) == ' ' || input(index+1) == ' '))
{
// prepare key by appending 2 characters
str = "" + input(index) + input(index+1)
// check if key already exists
// if exist just increment the value by 1
if(histogram.contains(str))
{
histogram(str) = histogram(str) + 1
}
// if key doesn't exist, insert it in map with count value
one
else
{
histogram(str) = 1
}
}
}
print("Histogram:")
// print the key value pair using map iterator foreach
histogram.keys.foreach{ key => print( " " + key + ": " +
histogram(key) + ",")}
}
}
Sample run 1:
Enter text:
this is a good thing
th: 2, hi: 2, is: 2, go: 1, oo: 1, od: 1, in: 1, ng: 1,
Sample run 2:
Enter text:
coooooool
co: 1, oo: 5, oo: 1, oo: 1, ol: 1,