Class: Node
- Inherits:
-
Object
- Object
- Node
- Defined in:
- lib/huffman.rb
Instance Attribute Summary collapse
-
#left ⇒ Object
Returns the value of attribute left.
-
#order ⇒ Object
Returns the value of attribute order.
-
#right ⇒ Object
Returns the value of attribute right.
-
#value ⇒ Object
Returns the value of attribute value.
-
#weight ⇒ Object
Returns the value of attribute weight.
Instance Method Summary collapse
-
#<=>(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.
-
#initialize(value, weight, order = 0, left = nil, right = nil) ⇒ Node
constructor
A new instance of Node.
- #leaf? ⇒ Boolean
- #traverse(code, hash) ⇒ Object
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
#left ⇒ Object
Returns the value of attribute left.
2 3 4 |
# File 'lib/huffman.rb', line 2 def left @left end |
#order ⇒ Object
Returns the value of attribute order.
2 3 4 |
# File 'lib/huffman.rb', line 2 def order @order end |
#right ⇒ Object
Returns the value of attribute right.
2 3 4 |
# File 'lib/huffman.rb', line 2 def right @right end |
#value ⇒ Object
Returns the value of attribute value.
2 3 4 |
# File 'lib/huffman.rb', line 2 def value @value end |
#weight ⇒ Object
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
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 |