class RhEntitlement::HuffmanEncoding

Attributes

input[RW]
lookup[RW]
output[RW]
root[RW]

Public Class Methods

new(input) click to toggle source
# File lib/rh_entitlement/huffman_encoding.rb, line 5
def initialize(input)
  @input = input
  @root = HuffmanNodeQueue.new(input).root
end

Public Instance Methods

[](char) click to toggle source
# File lib/rh_entitlement/huffman_encoding.rb, line 42
def [](char)
  encode(char)
end
decode(code) click to toggle source
# File lib/rh_entitlement/huffman_encoding.rb, line 18
def decode(code)
  lookup[code] || ""
end
decode_string(code) click to toggle source
# File lib/rh_entitlement/huffman_encoding.rb, line 28
def decode_string(code)
  code = code.to_s
  string = ''
  sub_code = ''
  code.each_char do |bit|
    sub_code += bit
    unless decode(sub_code).nil?
      string += decode(sub_code)
      sub_code = ''
    end
  end
  string
end
encode(entry) click to toggle source
# File lib/rh_entitlement/huffman_encoding.rb, line 14
def encode(entry)
  lookup.invert[entry] || ""
end
encode_list(list) click to toggle source
# File lib/rh_entitlement/huffman_encoding.rb, line 22
def encode_list(list)
  code = ''
  list.each { |c| code += encode(c) }
  code
end

Private Instance Methods

prepare_lookup() click to toggle source
# File lib/rh_entitlement/huffman_encoding.rb, line 48
def prepare_lookup
  lookup = {}
  @root.walk do |node, code|
    lookup[code] = node.symbol if node.leaf?
  end
  lookup
end