/**************************************************** * CS2510 Fall 2011 * Lecture #30 * Huffman Codes ****************************************************/ import tester.*; import java.util.*; // Huffman Codes class class Huffman { HashMap code; HashMap revcode; // generate Code void genCode(ArrayList in){ HashMap counts = new HashMap(); for(String s : in) { if (counts.containsKey(s)) { counts.put(s,counts.get(s)+1); } else { counts.put(s,1); } } PriorityQueue pq = new PriorityQueue(); for(String s : counts.keySet()) { pq.add(new Pair(s,counts.get(s))); } Pair first = pq.remove(); Tree t = new Leaf(first.s); while(!pq.isEmpty()) { Pair next = pq.remove(); } } // encode the given string list into the encoding ArrayList encode(ArrayList in) { } // decode the given encoding list into the original string list ArrayList decode(ArrayList in) { } } // A tree for representing the Huffman code interface Tree { } // The Leaf element of the tree class Leaf implements Tree{ String s; Leaf(String s) { super(); this.s = s; } } // The node element of the tree class Node implements Tree{ Tree left; Tree right; Node(Tree left, Tree right) { this.left = left; this.right = right; } } class Pair implements Comparable { String s; Integer i; Pair(String s, Integer i) { this.s = s; this.i = i; } // Smaller elements are "lesser" @Override public int compareTo(Pair o) { if (i < o.i) { return -1; } else if (i > o.i){ return 1; } else { return 0; } } public boolean equals(Object o) { if (o.getClass() == Pair.class) { Pair tmp = (Pair) o; return (s == tmp.s) && (i == tmp.i); } else { return false; } } } class LectureExamples { ArrayList input = new ArrayList(Arrays.asList("a","b","a","c","d","a","a","b")); Huffman huff = new Huffman(); // Clears testing state void reset() { huff = new Huffman(); } // Tests of genCode void testGenCode(Tester t) { reset(); huff.genCode(input); t.checkExpect(huff.code.containsKey("a"), true); t.checkExpect(huff.code.get("a"), 0); t.checkExpect(huff.code.get("d"), 111); t.checkExpect(huff.revcode.containsKey(0), true); t.checkExpect(huff.revcode.get(0), "a"); t.checkExpect(huff.revcode.get(110), "c"); } // Tests of encode void testEncode(Tester t) { reset(); huff.genCode(input); ArrayList in1 = new ArrayList(Arrays.asList("a","b","a")); ArrayList out1 = new ArrayList(Arrays.asList(0,10,0)); t.checkExpect(huff.encode(in1),out1); Iterator out1i = out1.iterator(); for(Integer i : huff.encode(in1)) { t.checkExpect(i,out1i.next()); } } // Tests of decode void testDecode(Tester t) { reset(); huff.genCode(input); ArrayList in1 = new ArrayList(Arrays.asList(0,10,0)); ArrayList out1 = new ArrayList(Arrays.asList("a","b","a")); t.checkExpect(huff.decode(in1),out1); Iterator out1i = out1.iterator(); for(String i : huff.decode(in1)) { t.checkExpect(i,out1i.next()); } } }