abstract class CodeTree
case class Fork(left: CodeTree, right: CodeTree, chars: List[Char], weight: Int) extends CodeTree
case class Leaf(char: Char, weight: Int) extends CodeTree
type Bit = Int
def decode(tree: CodeTree, bits: List[Bit]): List[Char] = {
if(!bits.isEmpty) {
bits.head match {
case 0 => tree match {
case Fork(l, r, _, _) => decode(l, bits.tail)
case Leaf(_, _) => chars(tree) ::: decode(frenchCode, bits.tail)
}
case 1 => tree match {
case Fork(l, r, _, _) => decode(r, bits.tail)
case Leaf(_, _) => chars(tree) ::: decode(frenchCode, bits.tail)
}
}
}
else Nil
}
val frenchCode: CodeTree = Fork(Fork(Fork(Leaf('s',121895),Fork(Leaf('d',56269),Fork(Fork(Fork(Leaf('x',5928),Leaf('j',8351),List('x','j'),14279),Leaf('f',16351),List('x','j','f'),30630),Fork(Fork(Fork(Fork(Leaf('z',2093),Fork(Leaf('k',745),Leaf('w',1747),List('k','w'),2492),List('z','k','w'),4585),Leaf('y',4725),List('z','k','w','y'),9310),Leaf('h',11298),List('z','k','w','y','h'),20608),Leaf('q',20889),List('z','k','w','y','h','q'),41497),List('x','j','f','z','k','w','y','h','q'),72127),List('d','x','j','f','z','k','w','y','h','q'),128396),List('s','d','x','j','f','z','k','w','y','h','q'),250291),Fork(Fork(Leaf('o',82762),Leaf('l',83668),List('o','l'),166430),Fork(Fork(Leaf('m',45521),Leaf('p',46335),List('m','p'),91856),Leaf('u',96785),List('m','p','u'),188641),List('o','l','m','p','u'),355071),List('s','d','x','j','f','z','k','w','y','h','q','o','l','m','p','u'),605362),Fork(Fork(Fork(Leaf('r',100500),Fork(Leaf('c',50003),Fork(Leaf('v',24975),Fork(Leaf('g',13288),Leaf('b',13822),List('g','b'),27110),List('v','g','b'),52085),List('c','v','g','b'),102088),List('r','c','v','g','b'),202588),Fork(Leaf('n',108812),Leaf('t',111103),List('n','t'),219915),List('r','c','v','g','b','n','t'),422503),Fork(Leaf('e',225947),Fork(Leaf('i',115465),Leaf('a',117110),List('i','a'),232575),List('e','i','a'),458522),List('r','c','v','g','b','n','t','e','i','a'),881025),List('s','d','x','j','f','z','k','w','y','h','q','o','l','m','p','u','r','c','v','g','b','n','t','e','i','a'),1486387)
val secret: List[Bit] = List(0,0,1,1,1,0,1,0,1,1,1,0,0,1,1,0,1,0,0,1,1,0,1,0,1,1,0,0,1,1,1,1,1,0,1,0,1,1,0,0,0,0,1,0,1,1,1,0,0,1,0,0,1,0,0,0,1,0,0,0,1,0,1)
def decodedSecret: List[Char] = decode(frenchCode, secret)ode here
我是scala的新手,现在学习模式匹配,我想做霍夫曼解码,现在我可以得到一个列表,但这是错误的答案,希望有人能找到错误。
答案 0 :(得分:4)
您的代码存在一些问题。
当你打一片叶子时,你不想消耗一点。如果代码中没有位,也应添加叶子的字符。
在解码方法中,您不想引用frenchCode,而是代码作为参数提供。
您可以通过模式匹配访问叶子的char,即case Leaf(codeChar,_)=> ...
顺便说一下。如果你开始在树上匹配,你的代码将更清洁。只有当它与叉子匹配时,你才会看到位列表的头部。
希望有所帮助。 ;)