Huffman code, according to each word in the text appears in the frequency of the number of weights, high-frequency weight value. Then each time fetch two minimum frequency spanning tree, and finally generate a big tree. From the root node to the path to the word, 0 on the left and 1 on the right,
function HFM () {var souce = [];function createnode (node) {var obj = {weight:0, parent:-1,lchild:-1,rchild:-1,value: '}; Return Object.assign (Obj,node);} This.addnode = function (node) {//Add word and frequency (weight value) Souce.push (CreateNode (node));} This.createtree = function () {//Huffman tree var huffnode = Json.parse (json.stringify (souce)); var n = Huffnode.length;var x1,x2; /Two index of least weight var m1,m2; Two values with minimum value for (var i = 0; i < n; i++) {m1 = m2 = Infinity; Initialize to maximum x1 = x2 =-1; for (var j = 0; J < N+i; J + +) {//search for two weights with the lowest value, and the parent node is-1 var item = huffnode[j];if (Item.weight < M1 && Item.Parent = =-1) {m2 = m1;x2 = X1;m1 = Item.weight;x1 = j;} else if (Item.weight < m2 && Item.Parent = =-1) {m2 = item.weight;; x2 = j;}} if (x1! =-1 && x2! =-1) {huffnode[x1].parent = n + i; Update parent Node Huffnode[x2].parent = n + i;//Create a new node huffnode[n+i] = CreateNode ({weight:m1+m2,lchild:x1,rchild:x2});}} return huffnode;}; This.getcode = function () {//Huffman code var n = souce.length; var tree = This.createtree (); var codes= {};for (var i = 0; i < n; i++) {var p = tree[i].parent;var code = "; var c = I;while (P! =-1) {//Iteration forward if (tree[p].lchild = = c) {code = 0 + code;} Else{code = 1 + code;} c = p;p = Tree[p].parent;} codes[Tree[i].value] = Code;console.log (tree[i].value, code);} return codes;}} var hfm = new Hfm (), Hfm.addnode ({weight:5,value: "a"}), Hfm.addnode ({weight:32,value: "B"}), Hfm.addnode ({weight:18, Value: "C"}); Hfm.addnode ({weight:7,value: "D"}), Hfm.addnode ({weight:25,value: "E"}), Hfm.addnode ({weight:13,value: "F"}); Console.log (Hfm.getcode ())
JS mysterious Telegraph Code---Havermann code