mramine364

huffman coding

Jun 26th, 2016
189
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. function huffman_codes(str){
  2.     let occ = [];
  3.     for(let i=0; i<str.length; i++){
  4.         let j=0;
  5.         for(; j<occ.length; j++){
  6.             if( occ[j].letter==str[i] ){
  7.                 break;
  8.             }
  9.         }
  10.         if( j==occ.length ){
  11.             occ.push( {
  12.                 right_child: null, left_child: null,
  13.                 letter: str[i], duplication: 1             
  14.             } );
  15.         }else{
  16.             occ[j].duplication++;
  17.         }
  18.     }
  19.     while( occ.length!=1 ){
  20.         occ.sort( function(a, b){
  21.             return a.duplication-b.duplication;
  22.         } );
  23.         let node=occ[0], node2=occ[1], parent;
  24.         if( node.duplication<node2.duplication ){
  25.             parent={
  26.                 right_child: node,
  27.                 left_child: node2,
  28.                 letter: null,
  29.                 duplication: node.duplication+node2.duplication
  30.             };
  31.         }else{
  32.             parent={
  33.                 right_child: node2,
  34.                 left_child: node,
  35.                 letter: null,
  36.                 duplication: node.duplication+node2.duplication
  37.             };
  38.         }
  39.         occ.splice(0,2);
  40.         occ.unshift(parent);
  41.     }
  42.     let codes=[];
  43.     _huffman_encode(occ[0], "", codes);
  44.     return codes;
  45. }
  46.  
  47. function _huffman_encode(par, str, t) {
  48.     if( par.letter==null ){    
  49.         _huffman_encode(par.left_child, str+0, t);
  50.         _huffman_encode(par.right_child, str+1, t);
  51.     }
  52.     else
  53.         t.push({ letter: par.letter, code: str});
  54. }
  55.  
  56. function huffman_encode(str, codes){
  57.     let encode="";
  58.     for(let i=0; i<str.length; i++){       
  59.         for(let j=0; j<codes.length; j++){
  60.             if( codes[j].letter==str[i] ){
  61.                 encode+=codes[j].code;
  62.                 break;
  63.             }
  64.         }      
  65.     }
  66.     return encode;
  67. }
  68.  
  69. function huffman_decode(encode, codes) {
  70.     let str="", decode="";
  71.     for(let i=0; i<encode.length; i++){
  72.         str+=encode[i];
  73.         for(let j=0; j<codes.length; j++){
  74.             if( codes[j].code==str ){
  75.                 decode+=codes[j].letter;
  76.                 str="";
  77.                 break;
  78.             }
  79.         }
  80.     }
  81.     return decode;
  82. }
Advertisement
Add Comment
Please, Sign In to add comment