Class: EasyEncoding::Huffman

Inherits:
Object
  • Object
show all
Defined in:
lib/easy_encoding/huffman.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(input) ⇒ Huffman

Returns a new instance of Huffman.



7
8
9
10
11
12
13
14
15
16
17
18
19
20
# File 'lib/easy_encoding/huffman.rb', line 7

def initialize(input)
  case input
  when Hash
    raise ArgumentError, 'summ of frequencies should eq 1' if input.values.reduce(:+) > 1
    @frequencies = input.sort_by { |_, value| value }.reverse.to_h
  when String
    @input = input
    @frequencies = calculate_frequencies(input)
  else
    raise ArgumentError, 'you must provide a hash or a string'
  end
  @root = create_tree(frequencies)
  @char_codes = generate_codes(root)
end

Instance Attribute Details

#char_codesObject (readonly)

Returns the value of attribute char_codes.



5
6
7
# File 'lib/easy_encoding/huffman.rb', line 5

def char_codes
  @char_codes
end

#frequenciesObject (readonly)

Returns the value of attribute frequencies.



5
6
7
# File 'lib/easy_encoding/huffman.rb', line 5

def frequencies
  @frequencies
end

#inputObject (readonly)

Returns the value of attribute input.



5
6
7
# File 'lib/easy_encoding/huffman.rb', line 5

def input
  @input
end

#rootObject (readonly)

Returns the value of attribute root.



5
6
7
# File 'lib/easy_encoding/huffman.rb', line 5

def root
  @root
end