scala coding to do the Huffman decoding, but wrong result -


 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 

i new scala, , learning pattern matching now, want huffman decoding, list, wrong answer, hope find mistake.

there several issues code.

  1. you not want consume bit when hit leaf. character of leaf should added if there no bit in code.

  2. in decode methode not want reference frenchcode, code instead given parameter.

  3. you can access char of leaf via pattern matching, i.e. case leaf(codechar, _) => ...

btw. code way cleaner if start matching on tree. if matches fork @ head of bit list.

hope helps. ;)


Popular posts from this blog