映射"WeightedTree"在斯卡拉 [英] Map a "WeightedTree" in Scala

查看:38
本文介绍了映射"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"在斯卡拉的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆