huffman_coding.sf 1.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556
  1. #!/usr/bin/ruby
  2. func walk(n, s, h) {
  3. n.exists('a') && (
  4. h{n{'a'}} = s;
  5. say "#{n{'a'}}: #{s}";
  6. return();
  7. );
  8. walk(n{'0'}, s+'0', h);
  9. walk(n{'1'}, s+'1', h);
  10. }
  11. func make_tree(text) {
  12. var letters = Hash.new;
  13. text.each { |c| letters{c} \\= 0 ++ };
  14. var nodes = letters.keys.map { |l|
  15. Hash.new('a' => l, 'freq' => letters{l})
  16. };
  17. var n = Hash.new;
  18. while (nodes.sort!{|a,b| a{'freq'} <=> b{'freq'} }.len > 1) {
  19. n = Hash.new('0' => nodes.shift, '1' => nodes.shift);
  20. n{'freq'} = (n{'0'}{'freq'} + n{'1'}{'freq'});
  21. nodes.append(n);
  22. }
  23. walk(n, '', n{'tree'} = Hash.new);
  24. return n;
  25. }
  26. func encode(s, t) {
  27. t = t{'tree'};
  28. s.split(1).join('' => {|c| t{c}});
  29. }
  30. func decode (enc, tree) {
  31. var n = tree;
  32. var out = '';
  33. enc.each {|bit|
  34. n = n{bit};
  35. n.has_key('a') && (
  36. out += n{'a'}; n = tree;
  37. );
  38. };
  39. return out;
  40. }
  41. var text = "this is an example for huffman encoding";
  42. var tree = make_tree(text);
  43. var enc = encode(text, tree);
  44. say enc;
  45. say decode(enc, tree);