又是一道入群題(Scala)
無意中挖到一道Scala入群題,寫一寫。
題目大意是:仿 sbt "inspect tree compile:compile" 命令的輸出實現文本樹的生成。題目詳細描述在這裡:Scala入群試題。
無需多言上代碼:
package treenncase class TreeNode[T](data: T, children: Seq[TreeNode[T]] = Nil)nnobject TreeShow {n def asciiDisplay(root: TreeNode[String]): Seq[String] = {n def doIt(node: TreeNode[String],n level: Int): Seq[String] = {n val s = level match {n case l if (l >= 2) => Seq(s" | ${" " * 2 * (l - 2)}+-${node.data}")n case _ => Seq(s"${" " * 2 * level}+-${node.data}")n }nn node.children match {n case Nil => sn case _ =>n node.children.foldLeft(s) {(acc, c) =>n if (c.children != Nil && level == 0) {n acc ++ doIt(c, level + 1) ++ Seq(" |")n } else {n acc ++ doIt(c, level + 1)n }n }n }n }nn val result = doIt(root, 0)nn result.last match {n case " |" =>n// val r = result.dropRight(1)n// println(r)n// rn result.dropRight(1)n case _ =>n// println(result)n resultn }n }nnn def main(args: Array[String]): Unit = {n asciiDisplay(TreeNode("Root",n children = List(TreeNode("level1-1"),n TreeNode("level1-2"),n TreeNode("level1-3")))).foreach(println)nn asciiDisplay(TreeNode("Root",n children = List(n TreeNode("level1-1",n children = TreeNode("level2-1", children = TreeNode("level3-1") :: Nil) :: Nil),n TreeNode("level1-2"),n TreeNode("level1-3")))).foreach(println)nn asciiDisplay(TreeNode("武功譜",n children = List(n TreeNode("少林",n children = TreeNode("伏虎拳") :: TreeNode("羅漢拳",n children = TreeNode("小羅漢拳") :: TreeNode("大羅漢拳") :: Nil) :: TreeNode("朝陽拳") :: Nil),n TreeNode("武當",n children = TreeNode("太極拳") :: TreeNode("太乙五行拳") :: Nil),n TreeNode("南拳",n children = TreeNode("虎形拳") :: TreeNode("鶴形拳") :: TreeNode("梅花樁") :: TreeNode("詠春拳",n children = TreeNode("小念頭") :: TreeNode("尋橋") :: TreeNode("標指") :: TreeNode("木人樁") :: Nil) :: Nil)))).foreach(println)n }n}n
編譯及運行:
scalac TreeShow.scalanscala tree.TreeShown
等等,居然還要測試用例。那就用ScalaTest好咧(做個樣子...
package treennimport org.scalatest.FunSuitennclass TreeTestSuite extends FunSuite {nn test("測試一") {n assert(List("+-Root", " +-level1-1", " +-level1-2", " +-level1-3")n == TreeShow.asciiDisplay(TreeNode("Root",n children = List(TreeNode("level1-1"),n TreeNode("level1-2"),n TreeNode("level1-3")))))n }nn test("測試二") {n assert(List("+-Root", " +-level1-1", " | +-level2-1", " | +-level3-1", " |", " +-level1-2", " +-level1-3")n == TreeShow.asciiDisplay(TreeNode("Root",n children = List(n TreeNode("level1-1",n children = TreeNode("level2-1", children = TreeNode("level3-1") :: Nil) :: Nil),n TreeNode("level1-2"),n TreeNode("level1-3")))))n }n}n
編譯、運行測試用例:
scalac -cp scalatest-app_2.12-3.0.4.jar;. TreeShow.scala TreeTestSuite.scalanscala -cp scalatest-app_2.12-3.0.4.jar;. org.scalatest.tools.Runner -s tree.TreeTestSuiten
Scala還是蠻符合我的胃口的,其實啥語言都符合才對......
推薦閱讀:
※Dotty 開發環境搭建
※在 Dotty 中模擬 Kotlin (1) —— 標籤返回
※如何評價 scala native?
※有哪些值得推薦的 Scala/Spark 編程 IDE?