Class: CodeCook::Greedy::HuffmanEncoding

Inherits:
Object
  • Object
show all
Defined in:
手写代码必备手册(Ruby版).rb

Overview

12.2 霍夫曼编码

require 'huffman.rb'
puts encoding = "Hello Huff".huffman
输出 => 1101010000100010110011111111

encoding.lookup.each do |code, char|
    puts "#{code} : #{char}"
end
输出 =>
00 : l 010 :
110 : H 011 : u 111 : f 100 : o 101 : e

Instance Attribute Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (HuffmanEncoding) initialize(input)

Returns a new instance of HuffmanEncoding



628
629
630
631
632
# File '手写代码必备手册(Ruby版).rb', line 628

def initialize(input)
    @input = input
    @root = NodeQueue.new(input).huffman_root
    @output = encode_string(input)
end

Instance Attribute Details

- (Object) input

Returns the value of attribute input



626
627
628
# File '手写代码必备手册(Ruby版).rb', line 626

def input
  @input
end

- (Object) lookup

Returns the value of attribute lookup



626
627
628
# File '手写代码必备手册(Ruby版).rb', line 626

def lookup
  @lookup
end

- (Object) output

Returns the value of attribute output



626
627
628
# File '手写代码必备手册(Ruby版).rb', line 626

def output
  @output
end

- (Object) root

Returns the value of attribute root



626
627
628
# File '手写代码必备手册(Ruby版).rb', line 626

def root
  @root
end

Instance Method Details

- (Object) [](char)



677
678
679
# File '手写代码必备手册(Ruby版).rb', line 677

def [](char)
    encode(char)
end

- (Object) decode(code)



647
648
649
# File '手写代码必备手册(Ruby版).rb', line 647

def decode(code)
    self.lookup[code]
end

- (Object) decode_string(code)



659
660
661
662
663
664
665
666
667
668
669
670
671
# File '手写代码必备手册(Ruby版).rb', line 659

def decode_string(code)
    code = code.to_s
    string = ''
    subcode = ''
    code.each_char do |bit|
        subcode += bit
        unless decode(subcode).nil?
            string += decode(subcode)
            subcode = ''
        end
    end
    string
end

- (Object) encode(char)



643
644
645
# File '手写代码必备手册(Ruby版).rb', line 643

def encode(char)
    self.lookup.invert[char]
end

- (Object) encode_string(string)



651
652
653
654
655
656
657
# File '手写代码必备手册(Ruby版).rb', line 651

def encode_string(string)
    code = ''
    string.each_char do |c|
        code += encode(c) 
    end
    code
end

- (Object) to_s



673
674
675
# File '手写代码必备手册(Ruby版).rb', line 673

def to_s
    @output
end