映射"WeightedTree"在斯卡拉

编程入门 行业动态 更新时间:2024-10-11 21:28:32
本文介绍了映射"WeightedTree"在斯卡拉的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

从此"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"在斯卡拉

本文发布于:2023-07-15 13:18:45,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1111440.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:斯卡   quot   WeightedTree

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!