从此"WeightedTree"我已经完成的特征,只剩下一个片段,有以下功能:
From this "WeightedTree" trait which I already completed, there is only one segment left, the following function:
写一个函数,该函数接收一个"WeightedTree".作为输入并返回"Map [Char,String]":对于叶子"中的每个字符,"WeightedTree"中的"WeightedTree"我们将其写为导致该特定字符的方式(向左"表示"0",向右表示"1"),如下所示:
Write a function, which recieves a "WeightedTree" as an input and returns a "Map[Char,String]: For every char in the "Leafs" of the "WeightedTree" we write the way it leads to that specific char ( going "left" means '0' and going right means '1' ), like this:
示例:内部(Inner(Leaf('a',4),5,Leaf('c',1)),10,Leaf('b',5))->映射('a'->'00','b'->'1','c'->'01')
EXAMPLE: Inner( Inner(Leaf('a',4), 5, Leaf('c',1) ), 10, Leaf('b',5) ) --> Map('a' -> "00", 'b' -> "1", 'c' -> "01")
代码:
trait WeightedTree { val weight: Int } case class Leaf(c: Char, weight: Int) extends WeightedTree case class Inner(left: WeightedTree, weight: Int, right: WeightedTree) extends WeightedTree object CodeCreator extends App { def treeToMap( codeTree: WeightedTree ): Map[Char, String] = ??? } 推荐答案朋友们的帮助下,我们将其放在一起,就成功了!
Friends helped out and we put this one together and it worked!
def treeToMap(codeTree: WeightedTree): Map[Char, String] = { def InnerLoop(innerTree: WeightedTree, path: String): Map[Char, String] = innerTree match { case Leaf(ch, c) => Map(ch -> path) case Inner(left, _: Int, right) => InnerLoop(left, path + "0") ++ InnerLoop(right, path + "1") } InnerLoop(codeTree, "") }更多推荐
映射"WeightedTree"在斯卡拉
发布评论