Class: Node

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

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(value, weight, order = 0, left = nil, right = nil) ⇒ Node

Returns a new instance of Node.



3
4
5
6
7
8
9
# File 'lib/huffman.rb', line 3

def initialize(value, weight, order=0, left=nil, right=nil)
  @value = value
  @weight = weight
  @left = left
  @right = right
  @order = order #actuality of the node
end

Instance Attribute Details

#leftObject

Returns the value of attribute left.



2
3
4
# File 'lib/huffman.rb', line 2

def left
  @left
end

#orderObject

Returns the value of attribute order.



2
3
4
# File 'lib/huffman.rb', line 2

def order
  @order
end

#rightObject

Returns the value of attribute right.



2
3
4
# File 'lib/huffman.rb', line 2

def right
  @right
end

#valueObject

Returns the value of attribute value.



2
3
4
# File 'lib/huffman.rb', line 2

def value
  @value
end

#weightObject

Returns the value of attribute weight.



2
3
4
# File 'lib/huffman.rb', line 2

def weight
  @weight
end

Instance Method Details

#<=>(other) ⇒ Object

the sorting order should be defined by weight and order of the internal node for obtaining Huffman code with minimum variance the most recent internal node should be later in the list



22
23
24
25
26
27
28
29
30
31
32
33
34
35
# File 'lib/huffman.rb', line 22

def <=>(other)
  if @weight < other.weight
    -1
  elsif  @weight > other.weight
    1
  else
    if @order < other.order
      return -1
    elsif @order > other.order
      return 1
    end
    0
  end
end

#leaf?Boolean

Returns:

  • (Boolean)


37
38
39
# File 'lib/huffman.rb', line 37

def leaf?
  @left.nil? && @right.nil?
end

#traverse(code, hash) ⇒ Object



11
12
13
14
15
16
17
18
# File 'lib/huffman.rb', line 11

def traverse(code, hash)
  if leaf?
    hash[@value] = code
  else
    @left.traverse(code + '1', hash)
    @right.traverse(code + '0', hash)
  end
end