Created
May 17, 2012 02:50
-
-
Save DanielleSucher/2715847 to your computer and use it in GitHub Desktop.
Huffman encoding for blog post
This file contains 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
def insert_branch(branch) | |
@encoded.each_with_index do |node, i| | |
if branch[-1] <= node[-1] | |
@encoded.insert i, branch | |
return @encoded | |
end | |
end | |
@encoded.push(branch) | |
end | |
def huffman_encode_trees | |
@encoded = @percentages.sort_by { |k,v| v } | |
until @encoded.length == 1 | |
a,b = @encoded.shift, @encoded.shift | |
branch = [a, b, (a[-1] + b[-1]).round(2)] | |
insert_branch branch | |
end | |
@encoded = @encoded[0] | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment