--Apple-Mail-4--1026478836
Content-Transfer-Encoding: 7bit
Content-Type: text/plain;
	charset-ASCII;
	format­´wed

Begin forwarded message:

> From: "Nicolas Modrzyk" <hellonico / gmail.com>
> Date: May 14, 2007 2:57:48 AM CDT
> To: submission / rubyquiz.com
> Subject: QUIZ 123 # Huffman Encoder
>
>

--Apple-Mail-4--1026478836
Content-Transfer-Encoding: 7bit
Content-Type: application/x-ruby;
	x-unix-mode66;
	nameffman_encode.rb
Content-Disposition: attachment;
	filenameffman_encode.rb

#! /usr/bin/ruby

# Ruby Quiz #123
# Copyright 2007 Nicolas Modrzyk

class Huffman
 
  def encode string, treel
    tree  reate_encoding_tree string if treeil
    @tree  ree
    encoded  "
    string.each_byte {|x| encoded << tree[x.chr].to_s}
    encoded
  end 

  def decode string, treel
    tree  tree if tree nil
    decoding_tree  ree.invert  
    decoded  "
    last_index  
    current_index  
    len  tring.length
  
    while (current_index < en) 
      s  tring.slice(last_index,current_index-last_index)
      #puts ":"+s+":"+last_index.to_s+":"+current_index.to_s
      if decoding_tree.has_key?(s)
        decoded << decoding_tree[s] 
        last_index  urrent_index
        #p "GOAL:" + s+":"+decoding_tree[s]
      end
      current_index + 
      
    end
  
    return decoded
    
  end

  def create_encoding_tree string
    tree  ount_frequency string
  
    s  1";
    count  ;
  
    tree.keys.sort {|a,b| tree[a]<ree[b]}.reverse.each do |k|
      if count 0
        tree[k]  0"  
      elsif (count (tree.keys.length-1))
        tree[k]   + "1"
      else
        tree[k]   + "0" 
        s << "1"
      end
      count + 
    end
  
    return tree
  end

  private
  
  def count_frequency string
    hash  ash.new
    string.each_byte {|x|
      if hash.key?(x.chr)
        hash[x.chr]  ash[x.chr].to_i + 1
      else
        hash[x.chr]  
      end
    }
    return hash
  end

  
end

def test string
  h  uffman.new
  puts string
  encoded  .encode string
  puts h.decode(encoded)
end


if $0 __FILE__
  h  uffman.new
  encoded  .encode(ARGV.join)
  puts encoded
  #puts h.decode(encoded)
else
  puts "Entering test mode"
  #string  ABRRKBAARAA"
  string2  I want this message to get encoded!"
  test string2
end
  

--Apple-Mail-4--1026478836
Content-Transfer-Encoding: 7bit
Content-Type: text/plain;
	charset-ASCII;
	format­´wed



--Apple-Mail-4--1026478836--