class HuffmanTree::Branch

A Branch is a kind of Node.

A Branch has, in addition to the attributes of a Node, a sequence of two Node objects called subtrees.

Its weight and width are the sums of the weights and widths, respectively, of its subtrees.

Its height is 1 plus the maximum of the heights of its subtrees.

Its offset the average of the offsets of the two subtrees, after their bounding boxes are merged into one.

Public Class Methods

new(weighted_tree0, weighted_tree1) click to toggle source

Assign two Node objects (subtrees) to a branch node.

The weight and width are the sums of the weights and widths, respectively, of the subtrees.

The height is 1 plus the maximum of the heights of the subtrees.

The offset the average of the offsets of the two subtrees, after their bounding boxes are merged into one.

Calls superclass method HuffmanTree::Node.new
# File huffman_tree.rb, line 163
def initialize(weighted_tree0, weighted_tree1)
    @subtrees = [weighted_tree0, weighted_tree1]
    raise ArgumentError, 'Not a Node' unless @subtrees[0].is_a? Node
    raise ArgumentError, 'Not a Node' unless @subtrees[1].is_a? Node
    weight = @subtrees.inject(0) { |sum, t| sum + t.weight }
    width = @subtrees.inject(0) { |sum, t| sum + t.width }
    height = 1 + [@subtrees[0].height, @subtrees[1].height].max
    offset = @subtrees[0].offset + @subtrees[1].offset
    offset = (offset + @subtrees[0].width) / 2.0
    super(weight, width, height, offset)
end

Public Instance Methods

[](index) click to toggle source

Reference a subtree of the Branch node.

# File huffman_tree.rb, line 186
def [](index)
    @subtrees[index.to_i]
end
draw(bits='') click to toggle source

Generate JavaScript to draw tree rooted at this node.

# File huffman_tree.rb, line 193
def draw(bits='')
    offset = @subtrees.map { |t| t.offset }
    width  = @subtrees.map { |t| t.width }
    " #{draw_link(bits)}
      draw_line(1, #{offset[0]}, 1, #{offset[1] + width[0]});
      translate(1, 0);
      #{@subtrees[0].draw(bits+'0')}
      translate(0, #{width[0]});
      #{@subtrees[1].draw(bits+'1')}
      translate(-1, #{-width[0]});
    "
end
margin(deepest, depth=0) click to toggle source

Length of the longest symbol in the deepest level of tree.

# File huffman_tree.rb, line 178
def margin(deepest, depth=0)
    [@subtrees[0].margin(deepest, depth+1),
     @subtrees[1].margin(deepest, depth+1)].max
end