SHARE
TWEET

Haffman main

a guest Oct 20th, 2018 134 Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. note
  2.     description: "Haffman application root class"
  3.     date: "$Date$"
  4.     revision: "$Revision$"
  5.  
  6. class
  7.     APPLICATION
  8.  
  9. inherit
  10.     ARGUMENTS
  11.  
  12. create
  13.     make
  14.  
  15. feature {NONE} -- Initialization
  16.  
  17. arr:LINKED_PRIORITY_QUEUE[PAIR]
  18. freq:ARRAY[INTEGER]
  19.     make
  20.             -- Run application.
  21.     local
  22.         s:STRING
  23.         t:PAIR
  24.         do
  25.             create freq.make_filled (0, 0, 255)
  26.             s:="abcdff"
  27.             set_freq(s)
  28.             make_tree
  29.             t:=arr.item
  30.             generate_codes(t, "")
  31.         end
  32.  
  33.     generate_codes(ch:PAIR; code:STRING)
  34.     do
  35.         if ch.char /= -1 then
  36.             print(ch.char.to_character_8.out + " = " + code + "%N")
  37.         end
  38.  
  39.         if attached ch.left as l then
  40.             generate_codes (l, code + "0")
  41.         end
  42.  
  43.         if attached ch.right as r then
  44.             generate_codes (r, code + "1")
  45.         end
  46.     end
  47.  
  48.     set_freq(s:STRING)
  49.     do
  50.         across
  51.                 s as char
  52.             loop
  53.                 freq[char.item.code] := freq[char.item.code] + 1
  54.             end
  55.     end
  56.  
  57.     make_tree
  58.     local
  59.         t,t1,t2:PAIR
  60.         i:INTEGER
  61.     do
  62.         create arr.make
  63.         from
  64.             i:=0
  65.         until
  66.             i>255
  67.         loop
  68.             if freq[i] > 0 then
  69.                 create t.make (i, freq[i])
  70.                 arr.extend (t)
  71.             end
  72.             i:= i + 1
  73.         end
  74.  
  75.  
  76.  
  77.         from
  78.         until
  79.             arr.count = 1
  80.         loop
  81.             t := arr.item.twin
  82.             arr.remove
  83.             t1 := arr.item.twin
  84.             arr.remove
  85.             create t2.make (-1, t.cnt+t1.cnt)
  86.             t2.set_left (t.char, t.cnt)
  87.             t2.set_right (t1.char, t1.cnt)
  88.             arr.extend (t2.twin)
  89.         end
  90.     end
  91.  
  92. end
RAW Paste Data
We use cookies for various purposes including analytics. By continuing to use Pastebin, you agree to our use of cookies as described in the Cookies Policy. OK, I Understand
Top