Data commit
This commit is contained in:
parent
7387c8f97b
commit
cb5bb5e222
199093 changed files with 3378972 additions and 0 deletions
28
Task/Align-columns/Scala/align-columns-1.scala
Normal file
28
Task/Align-columns/Scala/align-columns-1.scala
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
object ColumnAligner {
|
||||
val eol = System.getProperty("line.separator")
|
||||
def getLines(filename: String) = scala.io.Source.fromPath(filename).getLines(eol)
|
||||
def splitter(line: String) = line split '$'
|
||||
def getTable(filename: String) = getLines(filename) map splitter
|
||||
def fieldWidths(fields: Array[String]) = fields map (_ length)
|
||||
def columnWidths(txt: Iterator[Array[String]]) = (txt map fieldWidths).toList.transpose map (_ max)
|
||||
|
||||
def alignField(alignment: Char)(width: Int)(field: String) = alignment match {
|
||||
case 'l' | 'L' => "%-"+width+"s" format field
|
||||
case 'r' | 'R' => "%"+width+"s" format field
|
||||
case 'c' | 'C' => val padding = (width - field.length) / 2; " "*padding+"%-"+(width-padding)+"s" format field
|
||||
case _ => throw new IllegalArgumentException
|
||||
}
|
||||
|
||||
def align(aligners: List[String => String])(fields: Array[String]) =
|
||||
aligners zip fields map Function.tupled(_ apply _)
|
||||
|
||||
def alignFile(filename: String, alignment: Char) = {
|
||||
def table = getTable(filename)
|
||||
val aligners = columnWidths(table) map alignField(alignment)
|
||||
table map align(aligners) map (_ mkString " ")
|
||||
}
|
||||
|
||||
def printAlignedFile(filename: String, alignment: Char) {
|
||||
alignFile(filename, alignment) foreach println
|
||||
}
|
||||
}
|
||||
22
Task/Align-columns/Scala/align-columns-2.scala
Normal file
22
Task/Align-columns/Scala/align-columns-2.scala
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
def pad(s:String, i:Int, d:String) = {
|
||||
val padsize = (i-s.length).max(0)
|
||||
d match {
|
||||
case "left" => s+" "*padsize
|
||||
case "right" => " "*padsize+s
|
||||
case "center" => " "*(padsize/2) + s + " "*(padsize-padsize/2)
|
||||
}
|
||||
}
|
||||
|
||||
val lines = scala.io.Source.fromFile("c:\\text.txt").getLines.map(_.trim())
|
||||
val words = lines.map(_.split("\\$").toList).toList
|
||||
val lens = words.map(l => l.map(_.length)).toList
|
||||
|
||||
var maxlens = Map[Int,Int]() withDefaultValue 0
|
||||
lens foreach (l =>
|
||||
for(i <- (0 until l.length)){
|
||||
maxlens += i -> l(i).max(maxlens(i))
|
||||
}
|
||||
)
|
||||
|
||||
val padded = words map ( _.zipWithIndex.map{case(s,i)=>pad(s,maxlens(i),"center")+" "} )
|
||||
padded map (_.reduceLeft(_ + _)) foreach println
|
||||
Loading…
Add table
Add a link
Reference in a new issue