jinf Fei
Posts: 3
Nickname: jm8371
Registered: Mar, 2018
|
|
Re: Doubt in Scala Program
|
Posted: Mar 15, 2018 11:52 PM
|
|
import scala.io.Source
def widthOfLength(s: String) = s.length.toString.length
if (args.length > 0) { // read all line from file to list. val lines = Source.fromFile(args(0)).getLines().toList // reduceLeft function // all line at list (a1, a2, a3, a4, a5, ....) // c = a1.length max a2.length // c = c.length max a3.length // c = c.length max a4.length // c = c.length max a5.length // ... // return c val longestLine = lines.reduceLeft( (a, b) => if (a.length > b.length) a else b )
val maxWidth = widthOfLength( longestLine )
for (line <- lines) { // calculate we need space, for example: // line1: xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx // line2: | space |xxxxxxxxxxxxxxx // val numSpaces = maxWidth - widthOfLength(line) // space char val padding = " " * numSpaces
println(padding + line.length +"|"+ line) }
|
|