Skip to content

Instantly share code, notes, and snippets.

@timfel
Created May 6, 2009 20:06
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save timfel/107707 to your computer and use it in GitHub Desktop.
Save timfel/107707 to your computer and use it in GitHub Desktop.
def huffman filename
h = {}
open(filename) do |f|
f.read.each do |item|
unless h[item].nil?
h[item] += 1
else
h[item] = 1
end
end
end
while h.size > 1
h = output(h)
end
h
end
def output h
one = h.select { |k,v|
h[k] == h.values.min
}.first
h.delete(one[0])
two = h.select { |k,v|
h[k] == h.values.min
}.first
h.delete(two[0])
h[[one[0],two[0]].flatten] = one[1] + two[1]
h
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment