SlideShare a Scribd company logo
1 of 15
// Table.java: Huffman code frequency table
import java.io.*;
import java.util.TreeSet
class Table {
public final int MAXT = 100; // maximum number of different
symbols
public int currTableSize; // current size as table is constructed
public Entry[] tab; // the table array, not allocated
private Reader in; // internal file name for input stream
String file = ""; // the whole input file as a String
private boolean fileOpen = false; // is the file open yet?
private String fileName; // name of input file, if present
private int totalChars = 0; // total number of chars read
char markerChar = '@'; // sentinal at end of file
// Table: constructor, input parameter: input file name or null
public Table(String f) {
fileName = f;
currTableSize = 0;
tab = new Entry[MAXT];
}
// dumpTable: debug dump of contents of Table
public void dumpTable() {
int i;
System.out.println("nDump of Table ----->");
System.out.println(" Size: " + currTableSize);
for (i = 0; i < currTableSize; i++) {
System.out.println("Entry " + i + ". Symbol: " +
tab[i].symb + ", Weight: " + tab[i].weight +
", Representation: " + tab[i].rep);
}
System.out.println("----> End Dump of Tablen");
}
// getNextChar: fetches next char. Also opens input file
private char getNextChar() {
char ch = ' '; // = ' ' to keep compiler happy
if (!fileOpen) {
fileOpen = true;
if (fileName == null)
in = new InputStreamReader(System.in);
else {
try {
in = new FileReader(fileName);
} catch (IOException e) {
System.out.println("Exception opening " + fileName);
}
}
}
try {
ch = (char)in.read();
} catch (IOException e) {
System.out.println("Exception reading character");
}
return ch;
}
// buildFromFile: read file and build the map of the character
frequencies
private void buildFromFile(File file) throws
FileNotFoundException {
//
Map<String, Integer> freqMap = new BSTMap<String,
Integer>();Scanner scanner = new Scanner(file);
scanner.useDelimiter("");
String character;
while (scanner.hasNext()){
character = scanner.next();
Integer count = freqMap.get(character);
if (count == null){
count = Integer.valueOf(0);
}
freqMap.put(character, count+1);
}
// for each key, make a tree and load it into the priority queue
PriorityQueue<BinaryTree<CountPair>> treeQueue = new
PriorityQueue<BinaryTree<CountPair>>(freqMap.keySet().size(
), new CountPairTreeComparator
BinaryTree<CountPair> tmpTree;
for (String key: freqMap.keySet()){
int frequency = freqMap.get(key);
tmpTree = new BinaryTree<CountPair>(null, new
CountPair(key, frequency), null);
treeQueue.add(tmpTree);
}
Public interface Map<K extends Comparable<K>,V>
{
//This should load the value value into the map at the location
//associated with the key, replacing any preexisting value
//already associated with the key.
void put(K key, V value)
{
Map<String, Integer> freqMap = new BSTMap<String,
Integer>();Scanner scanner = new Scanner(file);
scanner.useDelimiter("");
String character;
while (scanner.hasNext()){
character = scanner.next();
Integer count = freqMap.get(character);
if (count == null){
count = Integer.valueOf(0);
}
freqMap.put(character, count+1);
}}
//This should fetch the value V associated with the key key, or
//null, if no match can be found.
int V get(K key)
{
int e = freqMap.get(key);
List l = new ListNode;
if( l.nextList.compareTo(e) != null){
V = e;
return V;
}
//This will report if there is a value associated with the value
//key in the map.
boolean containsKey(K key)
{
int e = freqMap.get(key);
List l = new ListNode;
if( l.nextList.compareTo(e) != null){
return true;
else
{
return false;
}
//This method should remove the entry associated with key and
//return the associated value. Return null if the key is
//not found.
public V remove(K key)
{
int e = freqMap.get(key);
List l = new ListNode;
if( l.nextList.compareTo(e) != null){
l.nextList = null;
return e;
}
else
{
return null;
}}
//This method should return a Set of all available keys in the
//map. You may use the java.util.TreeSet class to return
//these. You can build these on the fly using a traversal, or
//collect them as new keys are added to the map.
Set<K> keySet()
{
BinaryTree<CountPair> tmpTree;
while (void put(K key, V value) = 0)
{
Return K;
}}
//buildFromFile: fetch each character and build the Table
public void buildTable() {
char ch = getNextChar();
while (ch != 65535 && ch != markerChar) { // EOF or
special sentinal #
totalChars++;
file += ch;
int i = lookUp(ch);
if (i == -1) { // new entry
tab[currTableSize] = new Entry();
tab[currTableSize].symb = ch;
tab[currTableSize].weight = 1.0;
tab[currTableSize].rep = "";
currTableSize++;
}
else { // existing entry
tab[i].weight += 1.0;
}
// System.out.print(ch); // for debug
ch = getNextChar();
} // while
// finish calculating the weights
for (int j = 0; j < currTableSize; j++)
tab[j].weight /= (double)totalChars;
// System.out.println(); // for debug
}
// lookUp: loop up the next char in the Table tab
public int lookUp(char ch) {
for (int j = 0; j < currTableSize; j++)
if (tab[j].symb == ch) return j;
return -1;
}
// log2: Logarithm base 2
public double log2(double d) {
return Math.log(d) / Math.log(2.0);
}
// entropy: calculate entropy of the Table
public double entropy() {
double res = 0.0;
for (int i = 0; i < currTableSize; i++)
res += tab[i].weight * log2(1.0/tab[i].weight);
return res;
}
// aveCodeLen: calculate average code length
public double aveCodeLen() {
double res = 0.0;
for (int i = 0; i < currTableSize; i++)
res += tab[i].weight * tab[i].rep.length();
return res;
}
}
// TreeNode.java: node in the Huffman tree, used for
encode/decode
class TreeNode {
public double weight; // probability of symb occurring
public char symb; // the symbol to be encoded
public String rep; // string of 0's and 1's, the huffman code
word
public TreeNode left, right; // tree pointeres
public int step; // step number in construction (just for
displaying tree)
}
// ListNode.java: node in the linked list of trees, initially root
node trees
class ListNode {
public TreeNode hufftree;
public ListNode next;
}
// PriorityQueue.java: implement a priority queue as a linked
list of trees
// Initialize it as a linked list of singleton trees
class PriorityQueue {
private int initialCapacity;
public PriorityQueue(int initialCapacity,Comparator<? super E>
comparator)
{
ListNode list = null; // this points to the main list
// insert: void add(E item) insert new entry into the list
public void insert(TreeNode t) {
ListNode l = new ListNode();
l.hufftree = t;
l.next = list;
list = l;
}
//Obviously, this says if the queue is empty or not.
public boolean isEmpty()
{
ListNode l = new ListNode();
l.hufftree = t;
if(l.next == null)
{
Return true;
}
else
{
Return false;
}
list = l;
}
//This should return the size of the queue.
public int size()
{
int count = 0;
ListNode l = new ListNode();
if(l.hasnext()){
count++;
return count;
}
// buildList: create the initial list with singleton trees
public void buildList(Entry[] tab, int n) {
int i;
TreeNode tNode;
for (i = 0; i < n; i++) {
tNode = new TreeNode();
tNode.weight = tab[i].weight;
tNode.left = tNode.right = null;
tNode.symb = tab[i].symb;
tNode.rep = "";
insert(tNode);
}
}
//This returns the next item without removing it. This returns
//null if the queue is empty.
public E peek()
{
ListNode l = list;
while (l != null) {
return l.next;
}
// dumpList: debug dump of the list
public void dumpList() {
System.out.println("nDump of List ----->");
ListNode l = list;
while (l != null) {
System.out.print("Symb: " + l.hufftree.symb);
System.out.println(", Weight: " + l.hufftree.weight);
l = l.next;
}
System.out.println("----> End Dump of Listn");
}
//This removes the first item from the queue.
public E remove()
{
ListNode l;
if(l != null) {
l.next == null;
}
// least: Remove and return from the list tree with greatest
root weight
// sort of a pain in the ass to write
public TreeNode least() {
ListNode l, oldl, minl = null, oldminl = null; // = null: for
compiler
double minw = 1000000;
oldl = list;
l = list;
while (l != null) {
if (l.hufftree.weight < minw) {
minw = l.hufftree.weight;
oldminl = oldl;
minl = l;
}
oldl = l;
l = l.next;
}
if (minl == oldminl) {
list = list.next;
return minl.hufftree;
}
oldminl.next = minl.next;
return minl.hufftree;
}
}
// Huffman.java: the Huffman tree algorithm
import java.text.DecimalFormat;
class Huffman {
public TreeNode tree; // the decoding tree
public Table t; // the frequency and encoding table
public PriorityQueue p; // priority queue for building the
Huffman tree
private int depth; // depth variable for debug printing of tree
String encodedFile, decodedFile; // files as Strings
char markerChar = '@'; // sentinal at end of file
public DecimalFormat fourDigits = new
DecimalFormat("0.0000");
// Huffman: constructor, does all the work
public Huffman(String fileName) {
t = new Table(fileName);
t.buildTable();
// t.dumpTable();
p = new PriorityQueue();
p.buildList(t.tab, t.currTableSize);
// p.dumpList();
tree = huffman(t.currTableSize);
insertRep(tree, t.tab, t.currTableSize, "");
displayTree(tree);
t.dumpTable();
// System.out.println("nInput file (as a String):");
// System.out.println(t.file);
encodedFile = encode(t.file);
// System.out.println("nEncoded file (as a String):");
// System.out.println(encodedFile);
// decodedFile = decode(encodedFile);
// System.out.println("nDecoded file (as a String):");
// System.out.println(decodedFile);
System.out.println("Entropy: " + t.entropy() +
", Ave. Code Length: " + t.aveCodeLen());
}
// encode: translate the input file to binary Huffman file
public String encode(String file) {
String returnFile = ""; // encoded file to return (as a String)
for (int i = 0; i < file.length(); i++) {
int loc = t.lookUp(file.charAt(i));
if (loc == -1) {
System.out.println("Error in encode: can't find: " +
file.charAt(i));
System.exit(0);
}
returnFile += t.tab[loc].rep;
}
return returnFile;
}
// decode: translate the binary file (as a string) back to chars
public String decode(String file) {
String returnFile = ""; // decoded file to return (as a String)
TreeNode treeRef; // local tree variable to keep chasing into
tree
int i = 0; // index in the Huffman String
while (i < file.length()) { // keep going to end of String
treeRef = tree; // start at root of tree
while (true) {
if (treeRef.symb != markerChar) { // at a leaf node
returnFile += treeRef.symb;
break;
}
else if (file.charAt(i) == '0') { // go left with '0'
treeRef = treeRef.left;
i++;
}
else { // go right with '1'
treeRef = treeRef.right;
i++;
}
} // while (true)
} // while
return returnFile;
}
// huffman: construct the Huffman tree, for decoding
public TreeNode huffman(int n) {
int i;
TreeNode tree = null; // = null for compiler
for (i = 0; i < n-1; i++) {
tree = new TreeNode();
tree.left = p.least();
tree.left.step = i + 1; // just for displaying tree
tree.right = p.least();
tree.right.step = i + 1; // just for displaying tree
tree.weight = tree.left.weight +
tree.right.weight;
tree.symb = markerChar; // must not use '@' in input //file
tree.rep = "";
p.insert(tree);
}
return tree;
}
// displayTree: print out the tree, with initial and final
comments
public void displayTree(TreeNode tree) {
System.out.println("nDisplay of Huffman coding treen");
depth = 0;
displayTreeRecurs(tree);
}
// displayTreeRecurs: need recursive function for inorder
traveral
public void displayTreeRecurs(TreeNode tree) {
depth++; // depth of recursion
String s = "";
if (tree != null) {
s = display(tree.rep + "0");
System.out.println(s);
displayTreeRecurs(tree.left);
s = display(tree.rep);
System.out.print(s + "+---");
if (depth != 1) {
if (tree.symb == markerChar) System.out.print("+---");
}
System.out.print(tree.symb + ": " +
fourDigits.format(tree.weight) + ", " + tree.rep);
if (depth != 1)
System.out.println(" (step " + tree.step + ")");
else System.out.println();
displayTreeRecurs(tree.right);
s = display(tree.rep + "1");
System.out.println(s);
}
depth--;
}
// display: output blanks and verical lines to display tree
private String display(String rep) {
// tricky use of rep string to display correctly
String s = " ";
for (int i = 0; i < rep.length() - 1; i++) { // initial chars
if (rep.charAt(i) != rep.charAt(i+1) ) s += "|";
else s += " ";
s += " ";
}
return s;
}
// insertRep: tricky function to use Huffman tree to create
representation
public void insertRep(TreeNode tree, Entry tab[], int n, String
repr) {
//recursive function to insert Huffman codewords at each
node.
// this could just insert at the leaves.
String s1, s2;
tree.rep = repr;
if ((tree.left) == null && (tree.right) == null) {
for (int i = 0; i < n; i++)
if (tree.symb == tab[i].symb)
tab[i].rep = tree.rep;
return;
}
s1 = repr;
s1 += "0";
insertRep(tree.left, tab, n, s1); // recursive call to the left
s2 = repr;
s2 += "1";
insertRep(tree.right, tab, n, s2); // recursive call to the right
}
// main: doesn't do much; just feeds in input file name
public static void main(String[] args) {
Huffman huff;
// pass an input file name if present on command line
if (args.length > 0)
huff = new Huffman(args[0]);
else
huff = new Huffman(null);
}
}

More Related Content

Similar to Huffman Code Table Builder

PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdfPROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdfclimatecontrolsv
ย 
Stack queue
Stack queueStack queue
Stack queueHarry Potter
ย 
Stack queue
Stack queueStack queue
Stack queueYoung Alista
ย 
Stack queue
Stack queueStack queue
Stack queueFraboni Ec
ย 
Stack queue
Stack queueStack queue
Stack queueLuis Goldster
ย 
Stack queue
Stack queueStack queue
Stack queueHoang Nguyen
ย 
Stack queue
Stack queueStack queue
Stack queueJames Wong
ย 
Stack queue
Stack queueStack queue
Stack queueTony Nguyen
ย 
#ifndef MYLIST_H_ #define MYLIST_H_#includeiostream #include.docx
#ifndef MYLIST_H_ #define MYLIST_H_#includeiostream #include.docx#ifndef MYLIST_H_ #define MYLIST_H_#includeiostream #include.docx
#ifndef MYLIST_H_ #define MYLIST_H_#includeiostream #include.docxajoy21
ย 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. StreamsDEVTYPE
ย 
My question is pretty simple, I just want to know how to call my ope.pdf
My question is pretty simple, I just want to know how to call my ope.pdfMy question is pretty simple, I just want to know how to call my ope.pdf
My question is pretty simple, I just want to know how to call my ope.pdfjeetumordhani
ย 
In C++Add the function min as an abstract function to the classar.pdf
In C++Add the function min as an abstract function to the classar.pdfIn C++Add the function min as an abstract function to the classar.pdf
In C++Add the function min as an abstract function to the classar.pdffantoosh1
ย 
tested on eclipseDoublyLinkedList class.pdf
tested on eclipseDoublyLinkedList class.pdftested on eclipseDoublyLinkedList class.pdf
tested on eclipseDoublyLinkedList class.pdfshanki7
ย 
DS UNIT4_OTHER LIST STRUCTURES.docx
DS UNIT4_OTHER LIST STRUCTURES.docxDS UNIT4_OTHER LIST STRUCTURES.docx
DS UNIT4_OTHER LIST STRUCTURES.docxVeerannaKotagi1
ย 
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docxlab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docxDIPESH30
ย 
Keep getting a null pointer exception for some odd reasonim creati.pdf
Keep getting a null pointer exception for some odd reasonim creati.pdfKeep getting a null pointer exception for some odd reasonim creati.pdf
Keep getting a null pointer exception for some odd reasonim creati.pdfAroraRajinder1
ย 
Complete the provided partial C++ Linked List program. Main.cpp is g.pdf
Complete the provided partial C++ Linked List program. Main.cpp is g.pdfComplete the provided partial C++ Linked List program. Main.cpp is g.pdf
Complete the provided partial C++ Linked List program. Main.cpp is g.pdfrajkumarm401
ย 
How do you stop infinite loop Because I believe that it is making a.pdf
How do you stop infinite loop Because I believe that it is making a.pdfHow do you stop infinite loop Because I believe that it is making a.pdf
How do you stop infinite loop Because I believe that it is making a.pdffeelinggift
ย 
C++ projectMachine Problem 7 - HashingWrite a program to do the .pdf
C++ projectMachine Problem 7 - HashingWrite a program to do the .pdfC++ projectMachine Problem 7 - HashingWrite a program to do the .pdf
C++ projectMachine Problem 7 - HashingWrite a program to do the .pdffeelinggift
ย 

Similar to Huffman Code Table Builder (20)

PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdfPROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
PROBLEM STATEMENTIn this assignment, you will complete DoubleEnde.pdf
ย 
Stack queue
Stack queueStack queue
Stack queue
ย 
Stack queue
Stack queueStack queue
Stack queue
ย 
Stack queue
Stack queueStack queue
Stack queue
ย 
Stack queue
Stack queueStack queue
Stack queue
ย 
Stack queue
Stack queueStack queue
Stack queue
ย 
Stack queue
Stack queueStack queue
Stack queue
ย 
Stack queue
Stack queueStack queue
Stack queue
ย 
#ifndef MYLIST_H_ #define MYLIST_H_#includeiostream #include.docx
#ifndef MYLIST_H_ #define MYLIST_H_#includeiostream #include.docx#ifndef MYLIST_H_ #define MYLIST_H_#includeiostream #include.docx
#ifndef MYLIST_H_ #define MYLIST_H_#includeiostream #include.docx
ย 
6. Generics. Collections. Streams
6. Generics. Collections. Streams6. Generics. Collections. Streams
6. Generics. Collections. Streams
ย 
My question is pretty simple, I just want to know how to call my ope.pdf
My question is pretty simple, I just want to know how to call my ope.pdfMy question is pretty simple, I just want to know how to call my ope.pdf
My question is pretty simple, I just want to know how to call my ope.pdf
ย 
In C++Add the function min as an abstract function to the classar.pdf
In C++Add the function min as an abstract function to the classar.pdfIn C++Add the function min as an abstract function to the classar.pdf
In C++Add the function min as an abstract function to the classar.pdf
ย 
tested on eclipseDoublyLinkedList class.pdf
tested on eclipseDoublyLinkedList class.pdftested on eclipseDoublyLinkedList class.pdf
tested on eclipseDoublyLinkedList class.pdf
ย 
DS UNIT4_OTHER LIST STRUCTURES.docx
DS UNIT4_OTHER LIST STRUCTURES.docxDS UNIT4_OTHER LIST STRUCTURES.docx
DS UNIT4_OTHER LIST STRUCTURES.docx
ย 
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docxlab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
lab08build.bat@echo offclsset DRIVE_LETTER=1s.docx
ย 
Keep getting a null pointer exception for some odd reasonim creati.pdf
Keep getting a null pointer exception for some odd reasonim creati.pdfKeep getting a null pointer exception for some odd reasonim creati.pdf
Keep getting a null pointer exception for some odd reasonim creati.pdf
ย 
Complete the provided partial C++ Linked List program. Main.cpp is g.pdf
Complete the provided partial C++ Linked List program. Main.cpp is g.pdfComplete the provided partial C++ Linked List program. Main.cpp is g.pdf
Complete the provided partial C++ Linked List program. Main.cpp is g.pdf
ย 
week-14x
week-14xweek-14x
week-14x
ย 
How do you stop infinite loop Because I believe that it is making a.pdf
How do you stop infinite loop Because I believe that it is making a.pdfHow do you stop infinite loop Because I believe that it is making a.pdf
How do you stop infinite loop Because I believe that it is making a.pdf
ย 
C++ projectMachine Problem 7 - HashingWrite a program to do the .pdf
C++ projectMachine Problem 7 - HashingWrite a program to do the .pdfC++ projectMachine Problem 7 - HashingWrite a program to do the .pdf
C++ projectMachine Problem 7 - HashingWrite a program to do the .pdf
ย 

More from MARRY7

Part 1.....InstructionsSelect one of the age groups disc.docx
Part 1.....InstructionsSelect one of the age groups disc.docxPart 1.....InstructionsSelect one of the age groups disc.docx
Part 1.....InstructionsSelect one of the age groups disc.docxMARRY7
ย 
Part 1 โ€“ Add to Website PlanList at least three .docx
Part 1 โ€“ Add to Website PlanList at least three .docxPart 1 โ€“ Add to Website PlanList at least three .docx
Part 1 โ€“ Add to Website PlanList at least three .docxMARRY7
ย 
Part 1 True or False Questions. (10 questions at 1 point each).docx
Part 1 True or False Questions. (10 questions at 1 point each).docxPart 1 True or False Questions. (10 questions at 1 point each).docx
Part 1 True or False Questions. (10 questions at 1 point each).docxMARRY7
ย 
Part 11. Why is it so important in system engineering to become .docx
Part 11. Why is it so important in system engineering to become .docxPart 11. Why is it so important in system engineering to become .docx
Part 11. Why is it so important in system engineering to become .docxMARRY7
ย 
Part 1 Using the internet, search for commercial IDPS systems. What.docx
Part 1 Using the internet, search for commercial IDPS systems. What.docxPart 1 Using the internet, search for commercial IDPS systems. What.docx
Part 1 Using the internet, search for commercial IDPS systems. What.docxMARRY7
ย 
Part 1- Create an outline of the assignment below thenPart 2-1000 .docx
Part 1- Create an outline of the assignment below thenPart 2-1000 .docxPart 1- Create an outline of the assignment below thenPart 2-1000 .docx
Part 1- Create an outline of the assignment below thenPart 2-1000 .docxMARRY7
ย 
Part 1 Review QuestionsWhat is the difference between criminal la.docx
Part 1 Review QuestionsWhat is the difference between criminal la.docxPart 1 Review QuestionsWhat is the difference between criminal la.docx
Part 1 Review QuestionsWhat is the difference between criminal la.docxMARRY7
ย 
Part 1 Review QuestionsWhat is the difference between authenticat.docx
Part 1 Review QuestionsWhat is the difference between authenticat.docxPart 1 Review QuestionsWhat is the difference between authenticat.docx
Part 1 Review QuestionsWhat is the difference between authenticat.docxMARRY7
ย 
Part 1 SQLDatabase workScenarioDevelopment of a relationa.docx
Part 1 SQLDatabase workScenarioDevelopment of a relationa.docxPart 1 SQLDatabase workScenarioDevelopment of a relationa.docx
Part 1 SQLDatabase workScenarioDevelopment of a relationa.docxMARRY7
ย 
Part 1 Review QuestionsWhat functions constitute a complete infor.docx
Part 1 Review QuestionsWhat functions constitute a complete infor.docxPart 1 Review QuestionsWhat functions constitute a complete infor.docx
Part 1 Review QuestionsWhat functions constitute a complete infor.docxMARRY7
ย 
Part 1A persons lifestyle has a significant influence on the p.docx
Part 1A persons lifestyle has a significant influence on the p.docxPart 1A persons lifestyle has a significant influence on the p.docx
Part 1A persons lifestyle has a significant influence on the p.docxMARRY7
ย 
Part 1 Review QuestionsWhat is the definition of information secu.docx
Part 1 Review QuestionsWhat is the definition of information secu.docxPart 1 Review QuestionsWhat is the definition of information secu.docx
Part 1 Review QuestionsWhat is the definition of information secu.docxMARRY7
ย 
Part 1 Review QuestionsWhat is a security modelWhat are the es.docx
Part 1 Review QuestionsWhat is a security modelWhat are the es.docxPart 1 Review QuestionsWhat is a security modelWhat are the es.docx
Part 1 Review QuestionsWhat is a security modelWhat are the es.docxMARRY7
ย 
Part 1 Listed below are several key Supreme Court decisions that .docx
Part 1 Listed below are several key Supreme Court decisions that .docxPart 1 Listed below are several key Supreme Court decisions that .docx
Part 1 Listed below are several key Supreme Court decisions that .docxMARRY7
ย 
Part 1 Infrastructure DesignCreate an 8โ€“10-page infrastructur.docx
Part 1 Infrastructure DesignCreate an 8โ€“10-page infrastructur.docxPart 1 Infrastructure DesignCreate an 8โ€“10-page infrastructur.docx
Part 1 Infrastructure DesignCreate an 8โ€“10-page infrastructur.docxMARRY7
ย 
part 1 I attended an international conference on Biotechnology and .docx
part 1 I attended an international conference on Biotechnology and .docxpart 1 I attended an international conference on Biotechnology and .docx
part 1 I attended an international conference on Biotechnology and .docxMARRY7
ย 
Part 1 Chapter 7 Summary plus end of chapter discussion of Alfred.docx
Part 1 Chapter 7 Summary plus end of chapter discussion of Alfred.docxPart 1 Chapter 7 Summary plus end of chapter discussion of Alfred.docx
Part 1 Chapter 7 Summary plus end of chapter discussion of Alfred.docxMARRY7
ย 
Parent Involvement Plan This week you will create a Parent Involve.docx
Parent Involvement Plan This week you will create a Parent Involve.docxParent Involvement Plan This week you will create a Parent Involve.docx
Parent Involvement Plan This week you will create a Parent Involve.docxMARRY7
ย 
Parenting Practices Over GenerationsGeneration 1 Years children.docx
Parenting Practices Over GenerationsGeneration 1 Years children.docxParenting Practices Over GenerationsGeneration 1 Years children.docx
Parenting Practices Over GenerationsGeneration 1 Years children.docxMARRY7
ย 
ParamsThe interface must be pleasing to look at (a basic form wit.docx
ParamsThe interface must be pleasing to look at (a basic form wit.docxParamsThe interface must be pleasing to look at (a basic form wit.docx
ParamsThe interface must be pleasing to look at (a basic form wit.docxMARRY7
ย 

More from MARRY7 (20)

Part 1.....InstructionsSelect one of the age groups disc.docx
Part 1.....InstructionsSelect one of the age groups disc.docxPart 1.....InstructionsSelect one of the age groups disc.docx
Part 1.....InstructionsSelect one of the age groups disc.docx
ย 
Part 1 โ€“ Add to Website PlanList at least three .docx
Part 1 โ€“ Add to Website PlanList at least three .docxPart 1 โ€“ Add to Website PlanList at least three .docx
Part 1 โ€“ Add to Website PlanList at least three .docx
ย 
Part 1 True or False Questions. (10 questions at 1 point each).docx
Part 1 True or False Questions. (10 questions at 1 point each).docxPart 1 True or False Questions. (10 questions at 1 point each).docx
Part 1 True or False Questions. (10 questions at 1 point each).docx
ย 
Part 11. Why is it so important in system engineering to become .docx
Part 11. Why is it so important in system engineering to become .docxPart 11. Why is it so important in system engineering to become .docx
Part 11. Why is it so important in system engineering to become .docx
ย 
Part 1 Using the internet, search for commercial IDPS systems. What.docx
Part 1 Using the internet, search for commercial IDPS systems. What.docxPart 1 Using the internet, search for commercial IDPS systems. What.docx
Part 1 Using the internet, search for commercial IDPS systems. What.docx
ย 
Part 1- Create an outline of the assignment below thenPart 2-1000 .docx
Part 1- Create an outline of the assignment below thenPart 2-1000 .docxPart 1- Create an outline of the assignment below thenPart 2-1000 .docx
Part 1- Create an outline of the assignment below thenPart 2-1000 .docx
ย 
Part 1 Review QuestionsWhat is the difference between criminal la.docx
Part 1 Review QuestionsWhat is the difference between criminal la.docxPart 1 Review QuestionsWhat is the difference between criminal la.docx
Part 1 Review QuestionsWhat is the difference between criminal la.docx
ย 
Part 1 Review QuestionsWhat is the difference between authenticat.docx
Part 1 Review QuestionsWhat is the difference between authenticat.docxPart 1 Review QuestionsWhat is the difference between authenticat.docx
Part 1 Review QuestionsWhat is the difference between authenticat.docx
ย 
Part 1 SQLDatabase workScenarioDevelopment of a relationa.docx
Part 1 SQLDatabase workScenarioDevelopment of a relationa.docxPart 1 SQLDatabase workScenarioDevelopment of a relationa.docx
Part 1 SQLDatabase workScenarioDevelopment of a relationa.docx
ย 
Part 1 Review QuestionsWhat functions constitute a complete infor.docx
Part 1 Review QuestionsWhat functions constitute a complete infor.docxPart 1 Review QuestionsWhat functions constitute a complete infor.docx
Part 1 Review QuestionsWhat functions constitute a complete infor.docx
ย 
Part 1A persons lifestyle has a significant influence on the p.docx
Part 1A persons lifestyle has a significant influence on the p.docxPart 1A persons lifestyle has a significant influence on the p.docx
Part 1A persons lifestyle has a significant influence on the p.docx
ย 
Part 1 Review QuestionsWhat is the definition of information secu.docx
Part 1 Review QuestionsWhat is the definition of information secu.docxPart 1 Review QuestionsWhat is the definition of information secu.docx
Part 1 Review QuestionsWhat is the definition of information secu.docx
ย 
Part 1 Review QuestionsWhat is a security modelWhat are the es.docx
Part 1 Review QuestionsWhat is a security modelWhat are the es.docxPart 1 Review QuestionsWhat is a security modelWhat are the es.docx
Part 1 Review QuestionsWhat is a security modelWhat are the es.docx
ย 
Part 1 Listed below are several key Supreme Court decisions that .docx
Part 1 Listed below are several key Supreme Court decisions that .docxPart 1 Listed below are several key Supreme Court decisions that .docx
Part 1 Listed below are several key Supreme Court decisions that .docx
ย 
Part 1 Infrastructure DesignCreate an 8โ€“10-page infrastructur.docx
Part 1 Infrastructure DesignCreate an 8โ€“10-page infrastructur.docxPart 1 Infrastructure DesignCreate an 8โ€“10-page infrastructur.docx
Part 1 Infrastructure DesignCreate an 8โ€“10-page infrastructur.docx
ย 
part 1 I attended an international conference on Biotechnology and .docx
part 1 I attended an international conference on Biotechnology and .docxpart 1 I attended an international conference on Biotechnology and .docx
part 1 I attended an international conference on Biotechnology and .docx
ย 
Part 1 Chapter 7 Summary plus end of chapter discussion of Alfred.docx
Part 1 Chapter 7 Summary plus end of chapter discussion of Alfred.docxPart 1 Chapter 7 Summary plus end of chapter discussion of Alfred.docx
Part 1 Chapter 7 Summary plus end of chapter discussion of Alfred.docx
ย 
Parent Involvement Plan This week you will create a Parent Involve.docx
Parent Involvement Plan This week you will create a Parent Involve.docxParent Involvement Plan This week you will create a Parent Involve.docx
Parent Involvement Plan This week you will create a Parent Involve.docx
ย 
Parenting Practices Over GenerationsGeneration 1 Years children.docx
Parenting Practices Over GenerationsGeneration 1 Years children.docxParenting Practices Over GenerationsGeneration 1 Years children.docx
Parenting Practices Over GenerationsGeneration 1 Years children.docx
ย 
ParamsThe interface must be pleasing to look at (a basic form wit.docx
ParamsThe interface must be pleasing to look at (a basic form wit.docxParamsThe interface must be pleasing to look at (a basic form wit.docx
ParamsThe interface must be pleasing to look at (a basic form wit.docx
ย 

Recently uploaded

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxNirmalaLoungPoorunde1
ย 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementmkooblal
ย 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxSayali Powar
ย 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Celine George
ย 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsanshu789521
ย 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTiammrhaywood
ย 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Celine George
ย 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationnomboosow
ย 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceSamikshaHamane
ย 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfUjwalaBharambe
ย 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxJiesonDelaCerna
ย 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)eniolaolutunde
ย 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptxVS Mahajan Coaching Centre
ย 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxRaymartEstabillo3
ย 
call girls in Kamla Market (DELHI) ๐Ÿ” >เผ’9953330565๐Ÿ” genuine Escort Service ๐Ÿ”โœ”๏ธโœ”๏ธ
call girls in Kamla Market (DELHI) ๐Ÿ” >เผ’9953330565๐Ÿ” genuine Escort Service ๐Ÿ”โœ”๏ธโœ”๏ธcall girls in Kamla Market (DELHI) ๐Ÿ” >เผ’9953330565๐Ÿ” genuine Escort Service ๐Ÿ”โœ”๏ธโœ”๏ธ
call girls in Kamla Market (DELHI) ๐Ÿ” >เผ’9953330565๐Ÿ” genuine Escort Service ๐Ÿ”โœ”๏ธโœ”๏ธ9953056974 Low Rate Call Girls In Saket, Delhi NCR
ย 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Educationpboyjonauth
ย 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)โ€”โ€”โ€”โ€”IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)โ€”โ€”โ€”โ€”IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)โ€”โ€”โ€”โ€”IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)โ€”โ€”โ€”โ€”IMP.OF KSHARA ...M56BOOKSTORE PRODUCT/SERVICE
ย 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxiammrhaywood
ย 

Recently uploaded (20)

Employee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptxEmployee wellbeing at the workplace.pptx
Employee wellbeing at the workplace.pptx
ย 
Hierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of managementHierarchy of management that covers different levels of management
Hierarchy of management that covers different levels of management
ย 
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptxPOINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
POINT- BIOCHEMISTRY SEM 2 ENZYMES UNIT 5.pptx
ย 
Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17Computed Fields and api Depends in the Odoo 17
Computed Fields and api Depends in the Odoo 17
ย 
Presiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha electionsPresiding Officer Training module 2024 lok sabha elections
Presiding Officer Training module 2024 lok sabha elections
ย 
9953330565 Low Rate Call Girls In Rohini Delhi NCR
9953330565 Low Rate Call Girls In Rohini  Delhi NCR9953330565 Low Rate Call Girls In Rohini  Delhi NCR
9953330565 Low Rate Call Girls In Rohini Delhi NCR
ย 
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPTECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ECONOMIC CONTEXT - LONG FORM TV DRAMA - PPT
ย 
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
Incoming and Outgoing Shipments in 1 STEP Using Odoo 17
ย 
Interactive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communicationInteractive Powerpoint_How to Master effective communication
Interactive Powerpoint_How to Master effective communication
ย 
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdfTataKelola dan KamSiber Kecerdasan Buatan v022.pdf
TataKelola dan KamSiber Kecerdasan Buatan v022.pdf
ย 
Roles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in PharmacovigilanceRoles & Responsibilities in Pharmacovigilance
Roles & Responsibilities in Pharmacovigilance
ย 
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdfFraming an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
Framing an Appropriate Research Question 6b9b26d93da94caf993c038d9efcdedb.pdf
ย 
CELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptxCELL CYCLE Division Science 8 quarter IV.pptx
CELL CYCLE Division Science 8 quarter IV.pptx
ย 
Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)Software Engineering Methodologies (overview)
Software Engineering Methodologies (overview)
ย 
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions  for the students and aspirants of Chemistry12th.pptxOrganic Name Reactions  for the students and aspirants of Chemistry12th.pptx
Organic Name Reactions for the students and aspirants of Chemistry12th.pptx
ย 
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptxEPANDING THE CONTENT OF AN OUTLINE using notes.pptx
EPANDING THE CONTENT OF AN OUTLINE using notes.pptx
ย 
call girls in Kamla Market (DELHI) ๐Ÿ” >เผ’9953330565๐Ÿ” genuine Escort Service ๐Ÿ”โœ”๏ธโœ”๏ธ
call girls in Kamla Market (DELHI) ๐Ÿ” >เผ’9953330565๐Ÿ” genuine Escort Service ๐Ÿ”โœ”๏ธโœ”๏ธcall girls in Kamla Market (DELHI) ๐Ÿ” >เผ’9953330565๐Ÿ” genuine Escort Service ๐Ÿ”โœ”๏ธโœ”๏ธ
call girls in Kamla Market (DELHI) ๐Ÿ” >เผ’9953330565๐Ÿ” genuine Escort Service ๐Ÿ”โœ”๏ธโœ”๏ธ
ย 
Introduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher EducationIntroduction to ArtificiaI Intelligence in Higher Education
Introduction to ArtificiaI Intelligence in Higher Education
ย 
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)โ€”โ€”โ€”โ€”IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)โ€”โ€”โ€”โ€”IMP.OF KSHARA ...KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)โ€”โ€”โ€”โ€”IMP.OF KSHARA ...
KSHARA STURA .pptx---KSHARA KARMA THERAPY (CAUSTIC THERAPY)โ€”โ€”โ€”โ€”IMP.OF KSHARA ...
ย 
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptxECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ECONOMIC CONTEXT - PAPER 1 Q3: NEWSPAPERS.pptx
ย 

Huffman Code Table Builder

  • 1. // Table.java: Huffman code frequency table import java.io.*; import java.util.TreeSet class Table { public final int MAXT = 100; // maximum number of different symbols public int currTableSize; // current size as table is constructed public Entry[] tab; // the table array, not allocated private Reader in; // internal file name for input stream String file = ""; // the whole input file as a String private boolean fileOpen = false; // is the file open yet? private String fileName; // name of input file, if present private int totalChars = 0; // total number of chars read char markerChar = '@'; // sentinal at end of file // Table: constructor, input parameter: input file name or null public Table(String f) { fileName = f; currTableSize = 0; tab = new Entry[MAXT]; } // dumpTable: debug dump of contents of Table public void dumpTable() { int i; System.out.println("nDump of Table ----->"); System.out.println(" Size: " + currTableSize); for (i = 0; i < currTableSize; i++) { System.out.println("Entry " + i + ". Symbol: " + tab[i].symb + ", Weight: " + tab[i].weight + ", Representation: " + tab[i].rep); } System.out.println("----> End Dump of Tablen"); }
  • 2. // getNextChar: fetches next char. Also opens input file private char getNextChar() { char ch = ' '; // = ' ' to keep compiler happy if (!fileOpen) { fileOpen = true; if (fileName == null) in = new InputStreamReader(System.in); else { try { in = new FileReader(fileName); } catch (IOException e) { System.out.println("Exception opening " + fileName); } } } try { ch = (char)in.read(); } catch (IOException e) { System.out.println("Exception reading character"); } return ch; } // buildFromFile: read file and build the map of the character frequencies private void buildFromFile(File file) throws FileNotFoundException { // Map<String, Integer> freqMap = new BSTMap<String, Integer>();Scanner scanner = new Scanner(file); scanner.useDelimiter(""); String character; while (scanner.hasNext()){ character = scanner.next(); Integer count = freqMap.get(character);
  • 3. if (count == null){ count = Integer.valueOf(0); } freqMap.put(character, count+1); } // for each key, make a tree and load it into the priority queue PriorityQueue<BinaryTree<CountPair>> treeQueue = new PriorityQueue<BinaryTree<CountPair>>(freqMap.keySet().size( ), new CountPairTreeComparator BinaryTree<CountPair> tmpTree; for (String key: freqMap.keySet()){ int frequency = freqMap.get(key); tmpTree = new BinaryTree<CountPair>(null, new CountPair(key, frequency), null); treeQueue.add(tmpTree); } Public interface Map<K extends Comparable<K>,V> { //This should load the value value into the map at the location //associated with the key, replacing any preexisting value //already associated with the key. void put(K key, V value) { Map<String, Integer> freqMap = new BSTMap<String, Integer>();Scanner scanner = new Scanner(file); scanner.useDelimiter(""); String character; while (scanner.hasNext()){ character = scanner.next(); Integer count = freqMap.get(character); if (count == null){ count = Integer.valueOf(0); } freqMap.put(character, count+1); }}
  • 4. //This should fetch the value V associated with the key key, or //null, if no match can be found. int V get(K key) { int e = freqMap.get(key); List l = new ListNode; if( l.nextList.compareTo(e) != null){ V = e; return V; } //This will report if there is a value associated with the value //key in the map. boolean containsKey(K key) { int e = freqMap.get(key); List l = new ListNode; if( l.nextList.compareTo(e) != null){ return true; else { return false; } //This method should remove the entry associated with key and //return the associated value. Return null if the key is //not found. public V remove(K key) { int e = freqMap.get(key); List l = new ListNode; if( l.nextList.compareTo(e) != null){ l.nextList = null; return e; } else { return null;
  • 5. }} //This method should return a Set of all available keys in the //map. You may use the java.util.TreeSet class to return //these. You can build these on the fly using a traversal, or //collect them as new keys are added to the map. Set<K> keySet() { BinaryTree<CountPair> tmpTree; while (void put(K key, V value) = 0) { Return K; }} //buildFromFile: fetch each character and build the Table public void buildTable() { char ch = getNextChar(); while (ch != 65535 && ch != markerChar) { // EOF or special sentinal # totalChars++; file += ch; int i = lookUp(ch); if (i == -1) { // new entry tab[currTableSize] = new Entry(); tab[currTableSize].symb = ch; tab[currTableSize].weight = 1.0; tab[currTableSize].rep = ""; currTableSize++; } else { // existing entry tab[i].weight += 1.0; } // System.out.print(ch); // for debug ch = getNextChar(); } // while // finish calculating the weights for (int j = 0; j < currTableSize; j++) tab[j].weight /= (double)totalChars;
  • 6. // System.out.println(); // for debug } // lookUp: loop up the next char in the Table tab public int lookUp(char ch) { for (int j = 0; j < currTableSize; j++) if (tab[j].symb == ch) return j; return -1; } // log2: Logarithm base 2 public double log2(double d) { return Math.log(d) / Math.log(2.0); } // entropy: calculate entropy of the Table public double entropy() { double res = 0.0; for (int i = 0; i < currTableSize; i++) res += tab[i].weight * log2(1.0/tab[i].weight); return res; } // aveCodeLen: calculate average code length public double aveCodeLen() { double res = 0.0; for (int i = 0; i < currTableSize; i++) res += tab[i].weight * tab[i].rep.length(); return res; } } // TreeNode.java: node in the Huffman tree, used for encode/decode class TreeNode {
  • 7. public double weight; // probability of symb occurring public char symb; // the symbol to be encoded public String rep; // string of 0's and 1's, the huffman code word public TreeNode left, right; // tree pointeres public int step; // step number in construction (just for displaying tree) } // ListNode.java: node in the linked list of trees, initially root node trees class ListNode { public TreeNode hufftree; public ListNode next; } // PriorityQueue.java: implement a priority queue as a linked list of trees // Initialize it as a linked list of singleton trees class PriorityQueue { private int initialCapacity; public PriorityQueue(int initialCapacity,Comparator<? super E> comparator) { ListNode list = null; // this points to the main list // insert: void add(E item) insert new entry into the list public void insert(TreeNode t) { ListNode l = new ListNode(); l.hufftree = t; l.next = list; list = l; } //Obviously, this says if the queue is empty or not.
  • 8. public boolean isEmpty() { ListNode l = new ListNode(); l.hufftree = t; if(l.next == null) { Return true; } else { Return false; } list = l; } //This should return the size of the queue. public int size() { int count = 0; ListNode l = new ListNode(); if(l.hasnext()){ count++; return count; } // buildList: create the initial list with singleton trees public void buildList(Entry[] tab, int n) { int i; TreeNode tNode; for (i = 0; i < n; i++) { tNode = new TreeNode(); tNode.weight = tab[i].weight; tNode.left = tNode.right = null; tNode.symb = tab[i].symb; tNode.rep = ""; insert(tNode);
  • 9. } } //This returns the next item without removing it. This returns //null if the queue is empty. public E peek() { ListNode l = list; while (l != null) { return l.next; } // dumpList: debug dump of the list public void dumpList() { System.out.println("nDump of List ----->"); ListNode l = list; while (l != null) { System.out.print("Symb: " + l.hufftree.symb); System.out.println(", Weight: " + l.hufftree.weight); l = l.next; } System.out.println("----> End Dump of Listn"); } //This removes the first item from the queue. public E remove() { ListNode l; if(l != null) { l.next == null; } // least: Remove and return from the list tree with greatest root weight // sort of a pain in the ass to write public TreeNode least() { ListNode l, oldl, minl = null, oldminl = null; // = null: for compiler
  • 10. double minw = 1000000; oldl = list; l = list; while (l != null) { if (l.hufftree.weight < minw) { minw = l.hufftree.weight; oldminl = oldl; minl = l; } oldl = l; l = l.next; } if (minl == oldminl) { list = list.next; return minl.hufftree; } oldminl.next = minl.next; return minl.hufftree; } } // Huffman.java: the Huffman tree algorithm import java.text.DecimalFormat; class Huffman { public TreeNode tree; // the decoding tree public Table t; // the frequency and encoding table public PriorityQueue p; // priority queue for building the Huffman tree private int depth; // depth variable for debug printing of tree String encodedFile, decodedFile; // files as Strings char markerChar = '@'; // sentinal at end of file public DecimalFormat fourDigits = new DecimalFormat("0.0000"); // Huffman: constructor, does all the work
  • 11. public Huffman(String fileName) { t = new Table(fileName); t.buildTable(); // t.dumpTable(); p = new PriorityQueue(); p.buildList(t.tab, t.currTableSize); // p.dumpList(); tree = huffman(t.currTableSize); insertRep(tree, t.tab, t.currTableSize, ""); displayTree(tree); t.dumpTable(); // System.out.println("nInput file (as a String):"); // System.out.println(t.file); encodedFile = encode(t.file); // System.out.println("nEncoded file (as a String):"); // System.out.println(encodedFile); // decodedFile = decode(encodedFile); // System.out.println("nDecoded file (as a String):"); // System.out.println(decodedFile); System.out.println("Entropy: " + t.entropy() + ", Ave. Code Length: " + t.aveCodeLen()); } // encode: translate the input file to binary Huffman file public String encode(String file) { String returnFile = ""; // encoded file to return (as a String) for (int i = 0; i < file.length(); i++) { int loc = t.lookUp(file.charAt(i)); if (loc == -1) { System.out.println("Error in encode: can't find: " + file.charAt(i)); System.exit(0); } returnFile += t.tab[loc].rep; } return returnFile;
  • 12. } // decode: translate the binary file (as a string) back to chars public String decode(String file) { String returnFile = ""; // decoded file to return (as a String) TreeNode treeRef; // local tree variable to keep chasing into tree int i = 0; // index in the Huffman String while (i < file.length()) { // keep going to end of String treeRef = tree; // start at root of tree while (true) { if (treeRef.symb != markerChar) { // at a leaf node returnFile += treeRef.symb; break; } else if (file.charAt(i) == '0') { // go left with '0' treeRef = treeRef.left; i++; } else { // go right with '1' treeRef = treeRef.right; i++; } } // while (true) } // while return returnFile; } // huffman: construct the Huffman tree, for decoding public TreeNode huffman(int n) { int i; TreeNode tree = null; // = null for compiler for (i = 0; i < n-1; i++) { tree = new TreeNode(); tree.left = p.least(); tree.left.step = i + 1; // just for displaying tree
  • 13. tree.right = p.least(); tree.right.step = i + 1; // just for displaying tree tree.weight = tree.left.weight + tree.right.weight; tree.symb = markerChar; // must not use '@' in input //file tree.rep = ""; p.insert(tree); } return tree; } // displayTree: print out the tree, with initial and final comments public void displayTree(TreeNode tree) { System.out.println("nDisplay of Huffman coding treen"); depth = 0; displayTreeRecurs(tree); } // displayTreeRecurs: need recursive function for inorder traveral public void displayTreeRecurs(TreeNode tree) { depth++; // depth of recursion String s = ""; if (tree != null) { s = display(tree.rep + "0"); System.out.println(s); displayTreeRecurs(tree.left); s = display(tree.rep); System.out.print(s + "+---"); if (depth != 1) { if (tree.symb == markerChar) System.out.print("+---"); } System.out.print(tree.symb + ": " + fourDigits.format(tree.weight) + ", " + tree.rep); if (depth != 1)
  • 14. System.out.println(" (step " + tree.step + ")"); else System.out.println(); displayTreeRecurs(tree.right); s = display(tree.rep + "1"); System.out.println(s); } depth--; } // display: output blanks and verical lines to display tree private String display(String rep) { // tricky use of rep string to display correctly String s = " "; for (int i = 0; i < rep.length() - 1; i++) { // initial chars if (rep.charAt(i) != rep.charAt(i+1) ) s += "|"; else s += " "; s += " "; } return s; } // insertRep: tricky function to use Huffman tree to create representation public void insertRep(TreeNode tree, Entry tab[], int n, String repr) { //recursive function to insert Huffman codewords at each node. // this could just insert at the leaves. String s1, s2; tree.rep = repr; if ((tree.left) == null && (tree.right) == null) { for (int i = 0; i < n; i++) if (tree.symb == tab[i].symb) tab[i].rep = tree.rep; return; }
  • 15. s1 = repr; s1 += "0"; insertRep(tree.left, tab, n, s1); // recursive call to the left s2 = repr; s2 += "1"; insertRep(tree.right, tab, n, s2); // recursive call to the right } // main: doesn't do much; just feeds in input file name public static void main(String[] args) { Huffman huff; // pass an input file name if present on command line if (args.length > 0) huff = new Huffman(args[0]); else huff = new Huffman(null); } }