Skip to content

Instantly share code, notes, and snippets.

@DanielleSucher
Created May 17, 2012 02:50
Show Gist options
  • Save DanielleSucher/2715847 to your computer and use it in GitHub Desktop.
Save DanielleSucher/2715847 to your computer and use it in GitHub Desktop.
Huffman encoding for blog post
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