-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathsolution.js
More file actions
75 lines (67 loc) · 1.82 KB
/
solution.js
File metadata and controls
75 lines (67 loc) · 1.82 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
var countChars = function(input) {
var counts = {};
for (var i = 0; i < input.length; i++) {
var c = input[i];
counts[c] = counts[c] || 0;
counts[c]++;
}
return counts;
};
var makeHuffmanTree = function(input) {
var charCounts = countChars(input);
var pq = new PriorityQueue();
for (var c in charCounts) {
var n = charCounts[c];
var tree = new Tree([c]);
pq.insert(n, tree);
}
while (pq.size() > 1) {
var first = pq.extract();
var second = pq.extract();
var tree1 = first.val;
var tree2 = second.val;
var key1 = first.key;
var key2 = second.key;
var newTree = new Tree(tree1.val.concat(tree2.val));
newTree.left = tree1;
newTree.right = tree2;
pq.insert(key1+key2, newTree);
}
return pq.extract().val;
};
var encodeString = function(input, huffman) {
var output = "";
for (var i = 0; i < input.length; i++) {
var currentNode = huffman;
var nextCharacter = input[i];
while (currentNode.val.length > 1) {
if (currentNode.left.val.indexOf(nextCharacter) !== -1) {
currentNode = currentNode.left;
output += "0";
} else if (currentNode.right.val.indexOf(nextCharacter) !== -1) {
currentNode = currentNode.right;
output += "1";
} else {
throw new Error("Character " + nextCharacter + " is not in this Huffman tree.");
}
}
}
return output;
};
var decodeString = function(input, huffman) {
var output = "";
var currNode = huffman;
for (var currIdx = 0; currIdx < input.length; currIdx++) {
var currBit = input[currIdx];
if (currBit === "0") {
currNode = currNode.left;
} else if (currBit === "1") {
currNode = currNode.right;
}
if (currNode.val.length === 1) {
output += currNode.val[0];
currNode = huffman;
}
}
return output;
};