Created
June 28, 2015 19:35
-
-
Save avdg/510a0fa5310f593341fe to your computer and use it in GitHub Desktop.
Some random uncompleted huffman tree implementation
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Priority stack implementation over here https://github.com/avdg/screeps/blob/master/extensions/tools/library/priorityStack.js | |
// Assume AI.priorityStack = require(<path to priorityQueue>); | |
/** | |
* A basic huffman tree compression algorithm | |
* | |
* @param input String Input to convert | |
* | |
* @return string | |
*/ | |
function packHuffman(input) { | |
var frequency = {}; | |
var list = new AI.priorityStack(function(a, b) { | |
return b.frequency - a.frequency; | |
}); | |
var output = ""; | |
// Count input | |
for (var i = 0; i < input.length; i++) { | |
if (frequency[input[i]] === undefined) { | |
frequency[input[i]] = 1; | |
} else { | |
frequency[input[i]]++; | |
} | |
} | |
// Count frequency | |
for (var char in frequency) { | |
list.push({ | |
value: char, | |
frequency: frequency[char] | |
}); | |
} | |
// Build huffman tree | |
while (list.length > 1) { | |
var node = { | |
nodes: [list.pop(), list.pop()], | |
}; | |
node.frequency = node.nodes[0].frequency + node.nodes[1].frequency; | |
list.push(node); | |
} | |
// Only 1 item in tree, which is the huffman tree | |
list = list.pop(); | |
// Convert huffman codes for encoding | |
var table = {}; | |
var chars = []; | |
(function iterate (l, prefix) { | |
if (l.value === undefined) { | |
iterate(l.nodes[0], prefix + "0"); | |
iterate(l.nodes[1], prefix + "1"); | |
} else { | |
console.log('"' + l.value + '" with frequency ' + l.frequency + ': ' + prefix); | |
chars.push(l.value); | |
table[l.value] = prefix; | |
} | |
})(list, ""); | |
// Encode encode data- TODO this requires some 1/0 math wonders | |
// Encode string data itself - TODO this requires some 1/0 math wonders | |
for (var i = 0; i < input.length; i++) { | |
// TODO Yeah, convert that characters into bits! | |
// TODO Yeah, add those bits into a bitstring if needed! | |
} | |
// Build encoder data | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment