Advertisement
Guest User

Untitled

a guest
Apr 25th, 2018
60
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Java 7.01 KB | None | 0 0
  1. package huffman;
  2.  
  3. import java.io.BufferedReader;
  4. import java.io.File;
  5. import java.io.FileNotFoundException;
  6. import java.io.FileReader;
  7. import java.io.IOException;
  8. import java.util.ArrayList;
  9. import java.util.Collections;
  10. import java.util.Comparator;
  11. import java.util.HashMap;
  12. import java.util.List;
  13. import java.util.Map.Entry;
  14. import java.util.PriorityQueue;
  15. import java.util.Queue;
  16.  
  17. public class Main {
  18.     public static void main(String[] args) throws Exception {
  19.         File f = new File("illiad.txt");       
  20.         HuffmanEncoder he = new HuffmanEncoder();
  21.         String orig_text = new String(HuffmanEncoder.readFile(f));
  22.        
  23.         System.out.println("Getting Frequencies...");
  24.         String freq = he.getFrequencies(f);
  25.        
  26.         System.out.println("Building Tree...");
  27.         HuffTree ht = he.buildTree(f);
  28.  
  29.         System.out.println("Encoding File...");
  30.         String encoded = he.encodeFile(f, ht);
  31.  
  32.         System.out.println("Decoding File...");
  33.         String decoded = he.decodeFile(encoded, ht);
  34.        
  35.         System.out.println("Getting Dict File...");
  36.         String dict = he.traverseHuffmanTree(ht);
  37.          
  38.         System.out.println(freq);
  39.         System.out.println(dict);
  40.         System.out.println(orig_text.equals(decoded));
  41.     }
  42. }
  43.  
  44. class HuffmanEncoder implements HuffmanCoding {
  45.     public String getFrequencies(File inputFile) throws FileNotFoundException {
  46.         HashMap<Character, Integer> char_table = new HashMap<Character, Integer>();
  47.         byte[] fileContent = readFile(inputFile);
  48.         for (byte b : fileContent)
  49.         {
  50.             if (!char_table.containsKey((char)b))
  51.                 char_table.put((char)b, 0);
  52.             char_table.replace((char)b, char_table.get((char)b) + 1);
  53.         }
  54.        
  55.         String ret = "";
  56.         for (Entry<Character, Integer> e : char_table.entrySet())
  57.             ret += e.getKey() + " " + e.getValue() + "\n";
  58.         return ret;
  59.     }
  60.  
  61.     public HuffTree buildTree(File inputFile) throws FileNotFoundException, Exception {
  62.         HashMap<Character, Integer> char_table = new HashMap<Character, Integer>();
  63.         byte[] fileContent = readFile(inputFile);
  64.         for (byte b : fileContent) {
  65.             if (!char_table.containsKey((char)b))
  66.                 char_table.put((char)b, 0);
  67.             char_table.replace((char)b, char_table.get((char)b) + 1);
  68.         }
  69.         HuffTree tree = new HuffTree(char_table);
  70.         return tree;
  71.     }
  72.  
  73.     public String encodeFile(File inputFile, HuffTree huffTree) throws FileNotFoundException {
  74.         byte[] fileContent = readFile(inputFile);
  75.         byte[] output = new byte[fileContent.length * Byte.MAX_VALUE];
  76.         String en;
  77.         int j = 0;
  78.         for (int i = 0; i < fileContent.length; i++)
  79.         {
  80.             en = huffTree.translate((char)fileContent[i]);
  81.             for (byte c : en.getBytes())
  82.                 output[j++] = c;
  83.         }
  84.         byte[] out_string = new byte[j];
  85.         System.arraycopy(output, 0, out_string, 0, j);
  86.         return new String(out_string);
  87.     }
  88.  
  89.     public String decodeFile(String code, HuffTree huffTree) throws Exception {
  90.         byte[] output = new byte[code.length()];
  91.         String curr = "";
  92.         int j = 0;
  93.         for (byte b : code.getBytes()) {
  94.             curr += (char)b;
  95.             if (huffTree.translate(curr) != null) {
  96.                 output[j++] = (byte)huffTree.translate(curr).charValue();
  97.                 curr = "";
  98.             }
  99.         }
  100.         byte[] out_string = new byte[j];
  101.         System.arraycopy(output, 0, out_string, 0, j);
  102.         return new String(out_string);
  103.     }
  104.  
  105.     public String traverseHuffmanTree(HuffTree huffTree) throws Exception {
  106.         String ret = "";
  107.         HashMap<Character, String> dict = huffTree.getDict();
  108.         for (Entry<Character, String> e : dict.entrySet())
  109.             ret += e.getKey() + " " + e.getValue() + "\n";
  110.         return ret;
  111.     }
  112.    
  113.     public static byte[] readFile(File inputFile) throws FileNotFoundException {
  114.         String total_text = "";
  115.         BufferedReader br = new BufferedReader(new FileReader(inputFile));
  116.         try {
  117.             String line = null;
  118.             while ((line = br.readLine()) != null)
  119.                 total_text += line;
  120.         }
  121.         catch (IOException e){e.printStackTrace();}
  122.         return total_text.getBytes();
  123.     }
  124. }
  125.  
  126. class HuffTree {
  127.     Node home = null;
  128.     HashMap<Character, String> dict;
  129.     HashMap<String, Character> un_dict;
  130.    
  131.     public String translate(char c) {
  132.         if (!dict.containsKey(c))
  133.             return null;
  134.         return dict.get(c);
  135.     }
  136.    
  137.     public Character translate(String s) {
  138.         if (!un_dict.containsKey(s))
  139.             return null;
  140.         return un_dict.get(s);
  141.     }
  142.    
  143.     public HuffTree(HashMap<Character, Integer> char_table)
  144.     {
  145.         List<Entry<Character, Integer>> freq_list = sortChars(char_table);
  146.         Queue<Node> queue = new PriorityQueue<Node>();
  147.         for(Entry<Character, Integer> e : freq_list)
  148.             queue.add(new Node(e.getKey(), e.getValue()));
  149.         while (queue.size() > 1) {
  150.             Node b = queue.poll();
  151.             Node a = queue.poll();
  152.             Node new_node = new Node(a,b);
  153.             queue.add(new_node);
  154.         }
  155.         home = queue.poll();
  156.         dict = home.getDict();
  157.         un_dict = new HashMap<String, Character>();
  158.         for (Entry<Character, String> e : dict.entrySet())
  159.             un_dict.put(e.getValue(), e.getKey());
  160.     }
  161.    
  162.     public List<Entry<Character, Integer>> sortChars(HashMap<Character, Integer> char_table)
  163.     {
  164.         Comparator<Entry<Character, Integer>> valueComparator = new Comparator<Entry<Character,Integer>>() {    
  165.             @Override
  166.             public int compare(Entry<Character, Integer> e1, Entry<Character, Integer> e2) {
  167.                 return -Integer.compare(e1.getValue(), e2.getValue());
  168.             }
  169.         };
  170.         List<Entry<Character, Integer>> listOfEntries = new ArrayList<Entry<Character, Integer>>(char_table.entrySet());
  171.         Collections.sort(listOfEntries, valueComparator);
  172.         return listOfEntries;
  173.     }
  174.    
  175.     public HashMap<Character, String> getDict() {
  176.         return this.dict;
  177.     }
  178.    
  179.     public HashMap<String, Character> getUnDict() {
  180.         return this.un_dict;
  181.     }
  182.    
  183.     public void print() {
  184.         home.printNode(0);
  185.     }
  186. }
  187.  
  188. class Node implements Comparable<Node> {
  189.     char value = 0;
  190.     int weight;
  191.     Node parent = null;
  192.     Node a = null;
  193.     Node b = null;
  194.     String encoding = "";
  195.    
  196.     public Node(char value, int weight) {
  197.         this.value = value;
  198.         this.weight = weight;
  199.     }
  200.    
  201.     public Node(Node a, Node b) {
  202.         this.a = a;
  203.         a.parent = this;
  204.         this.b = b;
  205.         b.parent = this;
  206.         this.weight = a.weight + b.weight;
  207.     }
  208.    
  209.     public String getEncoding(String e)
  210.     {
  211.         String s = "";
  212.         if (parent != null) {
  213.             if (parent.a == this)
  214.                 s += "1";
  215.             else
  216.                 s += "0";
  217.             s = this.parent.getEncoding(e) + s;
  218.         }
  219.         return s;
  220.     }
  221.    
  222.     public HashMap<Character, String> getDict() {
  223.         HashMap<Character, String> dict = new HashMap<Character, String>();
  224.         if (value != 0)
  225.             dict.put(value, this.getEncoding(""));
  226.         else {
  227.             dict.putAll(a.getDict());
  228.             dict.putAll(b.getDict());
  229.         }
  230.         return dict;
  231.     }
  232.  
  233.     public void printNode(int t) {
  234.         for (int i = 0; i < t; i++)
  235.             System.out.print("\t");
  236.         System.out.print("(E=" + this.getEncoding(""));
  237.         if (this.value == 0)
  238.             System.out.print(", W="+ this.weight +")\n");
  239.         else
  240.             System.out.print(", V=" + this.value + ", W="+this.weight+")\n");          
  241.         if (this.a != null)
  242.             a.printNode(t + 1);
  243.         if (this.b != null)
  244.             b.printNode(t + 1);
  245.     }
  246.  
  247.     public int compareTo(Node arg0) {
  248.         if (this.weight != arg0.weight)
  249.             return Integer.compare(this.weight, arg0.weight);
  250.         else
  251.             return -Character.compare(this.value, arg0.value);
  252.     }
  253. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement