Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- function huffman_codes(str){
- let occ = [];
- for(let i=0; i<str.length; i++){
- let j=0;
- for(; j<occ.length; j++){
- if( occ[j].letter==str[i] ){
- break;
- }
- }
- if( j==occ.length ){
- occ.push( {
- right_child: null, left_child: null,
- letter: str[i], duplication: 1
- } );
- }else{
- occ[j].duplication++;
- }
- }
- while( occ.length!=1 ){
- occ.sort( function(a, b){
- return a.duplication-b.duplication;
- } );
- let node=occ[0], node2=occ[1], parent;
- if( node.duplication<node2.duplication ){
- parent={
- right_child: node,
- left_child: node2,
- letter: null,
- duplication: node.duplication+node2.duplication
- };
- }else{
- parent={
- right_child: node2,
- left_child: node,
- letter: null,
- duplication: node.duplication+node2.duplication
- };
- }
- occ.splice(0,2);
- occ.unshift(parent);
- }
- let codes=[];
- _huffman_encode(occ[0], "", codes);
- return codes;
- }
- function _huffman_encode(par, str, t) {
- if( par.letter==null ){
- _huffman_encode(par.left_child, str+0, t);
- _huffman_encode(par.right_child, str+1, t);
- }
- else
- t.push({ letter: par.letter, code: str});
- }
- function huffman_encode(str, codes){
- let encode="";
- for(let i=0; i<str.length; i++){
- for(let j=0; j<codes.length; j++){
- if( codes[j].letter==str[i] ){
- encode+=codes[j].code;
- break;
- }
- }
- }
- return encode;
- }
- function huffman_decode(encode, codes) {
- let str="", decode="";
- for(let i=0; i<encode.length; i++){
- str+=encode[i];
- for(let j=0; j<codes.length; j++){
- if( codes[j].code==str ){
- decode+=codes[j].letter;
- str="";
- break;
- }
- }
- }
- return decode;
- }
Advertisement
Add Comment
Please, Sign In to add comment