Reputation: 23
How to modify this code
package main
object Main extends App {
val lines = scala.io.Source.stdin.getLines //input the sentences, use "Enter" key for both changing line and end
val words = lines.flatMap(_.split("\\W+"))
val list2 = words.toVector.groupBy(_.length).mapValues(_.length)
val vectorOfLengths = (1 to list2.keys.max).map(length => list2.getOrElse(length, 0))
for ((count, length) <- vectorOfLengths.zipWithIndex)
println(f"${length+1} ${count} ${"*" * count}")
to realize the two goals:
flush-right align the numbers of words of each length
scale the length of the histogram bars so that the longest bar uses up the entire current width of the console
Upvotes: 0
Views: 61
Reputation: 52691
First, You need to add the formatting portion to the interpolated string. That would be %2s
if you wanted two characters of space.
${length + 1}%2s
Second, You'll need to scale each count
according to how big it is proportional to the longest bar:
val consoleWidth = 100
val maxCount = vectorOfLengths.max
for ((count, length) <- vectorOfLengths.zipWithIndex)
println(f"${length + 1}%2s: ${"#" * (count * consoleWidth / maxCount)}")
Upvotes: 1