SlideShare a Scribd company logo
1 of 8
Download to read offline
Modify HuffmanTree.java and HuffmanNode.java to allow the user to select the value of n 9 to
construct an n ary Huffman Tree. Once finished, verify the accuracy of your tree by running it
for the English Alphabet for n = 3, 4, 5, 6, 7, 8, 9. For each value of n, compute the average
codeword length. Write these in a table (n vs. ACW L(Cn)).
/ HuffmanTree.java
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.util.ArrayList;
import java.util.Scanner;
public class HuffmanTree {
public static void main(String[] args){
Scanner in = new Scanner(System.in);
System.out.print("Enter the file name: ");
String fileName = in.nextLine();
ArrayList nodes = new ArrayList<>();
ArrayList temp = new ArrayList<>();
try {
Scanner fin = new Scanner(new FileReader(fileName));
String symbol;
double prob;
while(fin.hasNext()){
symbol = fin.next();
prob = fin.nextDouble();
nodes.add(findInsertIndex(nodes, prob), new HuffmanNode(symbol, prob));
}
fin.close();
temp.addAll(nodes);
HuffmanNode root = createHuffmanTree(temp);
setCodeWords(root);
double avg = 0;
for (HuffmanNode node : nodes) {
System.out.println(node.getS() + ": " + node.getC() + ": " + node.getL());
avg += node.getL();
}
if(avg != 0)
avg /= nodes.size();
System.out.println("Average code length is: " + avg);
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
private static HuffmanNode createHuffmanTree(ArrayList nodes){
HuffmanNode root = null;
if(nodes.size() > 0) {
HuffmanNode node0, node1, node;
while (nodes.size() > 1) {
node0 = nodes.get(0);
node1 = nodes.get(1);
node = new HuffmanNode(null, node0.getP() + node1.getP());
node.setLeft(node0);
node.setRight(node1);
nodes.remove(0);
nodes.remove(0);
nodes.add(findInsertIndex(nodes, node.getP()), node);
}
root = nodes.get(0);
}
return root;
}
private static void setCodeWords(HuffmanNode root){
if(root != null){
setCodeWords(root, "");
}
}
private static void setCodeWords(HuffmanNode root, String codeWord){
if(root.getS() != null){
root.setC(codeWord);
root.setL(codeWord.length());
}
else{
setCodeWords(root.getLeft(), codeWord + "0");
setCodeWords(root.getRight(), codeWord + "1");
}
}
private static int findInsertIndex(ArrayList nodes, double prob){
for(int i = 0; i < nodes.size(); ++i){
if(prob < nodes.get(i).getP()){
return i;
}
}
return nodes.size();
}
}
// HuffmanNode.java
public class HuffmanNode {
private String S;
private double P;
private String C;
private int L;
private HuffmanNode left, right;
public HuffmanNode(String s, double p) {
S = s;
P = p;
}
public String getS() {
return S;
}
public void setS(String s) {
S = s;
}
public double getP() {
return P;
}
public void setP(double p) {
P = p;
}
public String getC() {
return C;
}
public void setC(String c) {
C = c;
}
public int getL() {
return L;
}
public void setL(int l) {
L = l;
}
public HuffmanNode getLeft() {
return left;
}
public void setLeft(HuffmanNode left) {
this.left = left;
}
public HuffmanNode getRight() {
return right;
}
public void setRight(HuffmanNode right) {
this.right = right;
}
}
//EnglishAlphabet.txt (symbols with probability)
Solution
public final class Huffman { private Huffman() {}; private static class HuffmanNode {
char ch; int frequency; HuffmanNode left; HuffmanNode right;
HuffmanNode(char ch, int frequency, HuffmanNode left, HuffmanNode right) { this.ch
= ch; this.frequency = frequency; this.left = left; this.right = right; }
} private static class HuffManComparator implements Comparator { @Override
public int compare(HuffmanNode node1, HuffmanNode node2) { return node1.frequency
- node2.frequency; } } /** * Compresses the string using huffman algorithm. *
The huffman tree and the huffman code are serialized to disk * * @param sentence
The sentence to be serialized * @throws FileNotFoundException If file is not found *
@throws IOException If IO exception occurs. */ public static void
compress(String sentence) throws FileNotFoundException, IOException { if (sentence ==
null) { throw new NullPointerException("Input sentence cannot be null."); } if
(sentence.length() == 0) { throw new IllegalArgumentException("The string should
atleast have 1 character."); } final Map charFreq = getCharFrequency(sentence);
final HuffmanNode root = buildTree(charFreq); final Map charCode =
generateCodes(charFreq.keySet(), root); final String encodedMessage =
encodeMessage(charCode, sentence); serializeTree(root);
serializeMessage(encodedMessage); } private static Map getCharFrequency(String
sentence) { final Map map = new HashMap(); for (int i = 0; i < sentence.length(); i++)
{ char ch = sentence.charAt(i); if (!map.containsKey(ch)) { map.put(ch,
1); } else { int val = map.get(ch); map.put(ch, ++val); } }
return map; } /** * Map map * Some implementation of that treeSet is passed
as parameter. * @param map */ private static HuffmanNode buildTree(Map map) {
final Queue nodeQueue = createNodeQueue(map); while (nodeQueue.size() > 1) {
final HuffmanNode node1 = nodeQueue.remove(); final HuffmanNode node2 =
nodeQueue.remove(); HuffmanNode node = new HuffmanNode('0', node1.frequency
+ node2.frequency, node1, node2); nodeQueue.add(node); } // remove it to
prevent object leak. return nodeQueue.remove(); } private static Queue
createNodeQueue(Map map) { final Queue pq = new PriorityQueue(11, new
HuffManComparator()); for (Entry entry : map.entrySet()) { pq.add(new
HuffmanNode(entry.getKey(), entry.getValue(), null, null)); } return pq; }
private static Map generateCodes(Set chars, HuffmanNode node) { final Map map = new
HashMap(); doGenerateCode(node, map, ""); return map; } private static void
doGenerateCode(HuffmanNode node, Map map, String s) { if (node.left == null &&
node.right == null) { map.put(node.ch, s); return; }
doGenerateCode(node.left, map, s + '0'); doGenerateCode(node.right, map, s + '1' ); }
private static String encodeMessage(Map charCode, String sentence) { final StringBuilder
stringBuilder = new StringBuilder(); for (int i = 0; i < sentence.length(); i++) {
stringBuilder.append(charCode.get(sentence.charAt(i))); } return
stringBuilder.toString(); } private static void serializeTree(HuffmanNode node) throws
FileNotFoundException, IOException { final BitSet bitSet = new BitSet(); try
(ObjectOutputStream oosTree = new ObjectOutputStream(new
FileOutputStream("/Users/ap/Desktop/tree"))) { try (ObjectOutputStream oosChar =
new ObjectOutputStream(new FileOutputStream("/Users/ap/Desktop/char"))) {
IntObject o = new IntObject(); preOrder(node, oosChar, bitSet, o);
bitSet.set(o.bitPosition, true); // padded to mark end of bit set relevant for deserialization.
oosTree.writeObject(bitSet); } } } private static class IntObject { int
bitPosition; } /* * Algo: * 1. Access the node * 2. Register the value in bit set.
* * * here true and false dont correspond to left branch and right branch. * there, *
- true means "a branch originates from leaf" * - false mens "a branch originates from non-
left". * * Also since branches originate from some node, the root node must be provided
as source * or starting point of initial branches. * * Diagram and how an bit set
would look as a result. * (source node) * /  * true
true * /  * (leaf node) (leaf node) * | | *
false false * | | * * So now a bit set looks like
[false, true, false, true] * */ private static void preOrder(HuffmanNode node,
ObjectOutputStream oosChar, BitSet bitSet, IntObject intObject) throws IOException { if
(node.left == null && node.right == null) { bitSet.set(intObject.bitPosition++, false); //
register branch in bitset oosChar.writeChar(node.ch); return;
// DONT take the branch. } bitSet.set(intObject.bitPosition++, true); // register
branch in bitset preOrder(node.left, oosChar, bitSet, intObject); // take the branch.
bitSet.set(intObject.bitPosition++, true); // register branch in bitset
preOrder(node.right, oosChar, bitSet, intObject); // take the branch. } private static void
serializeMessage(String message) throws IOException { final BitSet bitSet =
getBitSet(message); try (ObjectOutputStream oos = new ObjectOutputStream(new
FileOutputStream("/Users/ap/Desktop/encodedMessage"))){ oos.writeObject(bitSet);
} } private static BitSet getBitSet(String message) { final BitSet bitSet = new
BitSet(); int i = 0; for (i = 0; i < message.length(); i++) { if (message.charAt(i)
== '0') { bitSet.set(i, false); } else { bitSet.set(i, true); }
} bitSet.set(i, true); // dummy bit set to know the length return bitSet; } /** *
Retrieves back the original string. * * * @return The original
uncompressed string * @throws FileNotFoundException If the file is not found *
@throws ClassNotFoundException If class is not found * @throws IOException If
IOException occurs */ public static String expand() throws FileNotFoundException,
ClassNotFoundException, IOException { final HuffmanNode root = deserializeTree();
return decodeMessage(root); } private static HuffmanNode deserializeTree() throws
FileNotFoundException, IOException, ClassNotFoundException { try (ObjectInputStream
oisBranch = new ObjectInputStream(new FileInputStream("/Users/ap/Desktop/tree"))) {
try (ObjectInputStream oisChar = new ObjectInputStream(new
FileInputStream("/Users/ap/Desktop/char"))) { final BitSet bitSet = (BitSet)
oisBranch.readObject(); return preOrder(bitSet, oisChar, new IntObject()); }
} } /* * Construct a tree from: * input [false, true, false, true, (dummy true to mark
the end of bit set)] * The input is constructed from preorder traversal * * Algo: * 1
Create the node. * 2. Read what is registered in bitset, and decide if created node is supposed
to be a leaf or non-leaf * */ private static HuffmanNode preOrder(BitSet bitSet,
ObjectInputStream oisChar, IntObject o) throws IOException { // created the node before
reading whats registered. final HuffmanNode node = new HuffmanNode('0', 0, null,
null); // reading whats registered and determining if created node is the leaf or non-leaf.
if (!bitSet.get(o.bitPosition)) { o.bitPosition++; // feed the next position to the
next stack frame by doing computation before preOrder is called. node.ch =
oisChar.readChar(); return node; } o.bitPosition = o.bitPosition + 1; // feed
the next position to the next stack frame by doing computation before preOrder is called.
node.left = preOrder(bitSet, oisChar, o); o.bitPosition = o.bitPosition + 1; // feed the next
position to the next stack frame by doing computation before preOrder is called. node.right
= preOrder(bitSet, oisChar, o); return node; } private static String
decodeMessage(HuffmanNode node) throws FileNotFoundException, IOException,
ClassNotFoundException { try (ObjectInputStream ois = new ObjectInputStream(new
FileInputStream("/Users/ameya.patil/Desktop/encodedMessage"))) { final BitSet bitSet
= (BitSet) ois.readObject(); final StringBuilder stringBuilder = new StringBuilder();
for (int i = 0; i < (bitSet.length() - 1);) { HuffmanNode temp = node; //
since huffman code generates full binary tree, temp.right is certainly null if temp.left is null.
while (temp.left != null) { if (!bitSet.get(i)) { temp = temp.left;
} else { temp = temp.right; } i = i + 1;
} stringBuilder.append(temp.ch); } return stringBuilder.toString();
} } public static void main(String[] args) throws FileNotFoundException, IOException,
ClassNotFoundException { // even number of characters Huffman.compress("some");
Assert.assertEquals("some", Huffman.expand()); // odd number of characters
Huffman.compress("someday"); Assert.assertEquals("someday", Huffman.expand());
// repeating even number of characters + space + non-ascii Huffman.compress("some
some#"); Assert.assertEquals("some some#", Huffman.expand()); // odd number of
characters + space + non-ascii Huffman.compress("someday someday&");
Assert.assertEquals("someday someday&", Huffman.expand()); } }

More Related Content

Similar to Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf

ANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdfANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdfanukoolelectronics
 
java question Fill the add statement areaProject is to wo.pdf
java question Fill the add statement areaProject is to wo.pdfjava question Fill the add statement areaProject is to wo.pdf
java question Fill the add statement areaProject is to wo.pdfdbrienmhompsonkath75
 
Step 1 The Pair Class Many times in writing software we come across p.pdf
Step 1 The Pair Class Many times in writing software we come across p.pdfStep 1 The Pair Class Many times in writing software we come across p.pdf
Step 1 The Pair Class Many times in writing software we come across p.pdfformaxekochi
 
package singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfpackage singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfamazing2001
 
Frequency .java Word frequency counter package frequ.pdf
Frequency .java  Word frequency counter  package frequ.pdfFrequency .java  Word frequency counter  package frequ.pdf
Frequency .java Word frequency counter package frequ.pdfarshiartpalace
 
Please read the comment ins codeExpressionTree.java-------------.pdf
Please read the comment ins codeExpressionTree.java-------------.pdfPlease read the comment ins codeExpressionTree.java-------------.pdf
Please read the comment ins codeExpressionTree.java-------------.pdfshanki7
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6Dmitry Soshnikov
 
JAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdfJAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdffantasiatheoutofthef
 
Java Question help needed In the program Fill the Add statements.pdf
Java Question  help needed In the program Fill the Add statements.pdfJava Question  help needed In the program Fill the Add statements.pdf
Java Question help needed In the program Fill the Add statements.pdfkamdinrossihoungma74
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVMRafael Winterhalter
 
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
 
hi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdfhi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdfarchgeetsenterprises
 
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfCreat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfaromanets
 
Please help write BinaryTree-java Thank you! Create a class BinaryTr.pdf
Please help write BinaryTree-java Thank you!   Create a class BinaryTr.pdfPlease help write BinaryTree-java Thank you!   Create a class BinaryTr.pdf
Please help write BinaryTree-java Thank you! Create a class BinaryTr.pdfinfo750646
 
I need to adjust this Huffman code so that it asks for the user to i.pdf
I need to adjust this Huffman code so that it asks for the user to i.pdfI need to adjust this Huffman code so that it asks for the user to i.pdf
I need to adjust this Huffman code so that it asks for the user to i.pdfjibinsh
 
usingpackage util;import java.util.;This class implements.pdf
usingpackage util;import java.util.;This class implements.pdfusingpackage util;import java.util.;This class implements.pdf
usingpackage util;import java.util.;This class implements.pdfinfo335653
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2Mohamed Krar
 

Similar to Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf (20)

ANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdfANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
ANSimport java.util.Scanner; class Bina_node { Bina_node .pdf
 
java question Fill the add statement areaProject is to wo.pdf
java question Fill the add statement areaProject is to wo.pdfjava question Fill the add statement areaProject is to wo.pdf
java question Fill the add statement areaProject is to wo.pdf
 
Step 1 The Pair Class Many times in writing software we come across p.pdf
Step 1 The Pair Class Many times in writing software we come across p.pdfStep 1 The Pair Class Many times in writing software we come across p.pdf
Step 1 The Pair Class Many times in writing software we come across p.pdf
 
package singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdfpackage singlylinkedlist; public class Node { public String valu.pdf
package singlylinkedlist; public class Node { public String valu.pdf
 
Lezione03
Lezione03Lezione03
Lezione03
 
Lezione03
Lezione03Lezione03
Lezione03
 
Frequency .java Word frequency counter package frequ.pdf
Frequency .java  Word frequency counter  package frequ.pdfFrequency .java  Word frequency counter  package frequ.pdf
Frequency .java Word frequency counter package frequ.pdf
 
Please read the comment ins codeExpressionTree.java-------------.pdf
Please read the comment ins codeExpressionTree.java-------------.pdfPlease read the comment ins codeExpressionTree.java-------------.pdf
Please read the comment ins codeExpressionTree.java-------------.pdf
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
 
JAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdfJAVA OOP project; desperately need help asap im begging.Been stuck.pdf
JAVA OOP project; desperately need help asap im begging.Been stuck.pdf
 
What's New In C# 7
What's New In C# 7What's New In C# 7
What's New In C# 7
 
Java Question help needed In the program Fill the Add statements.pdf
Java Question  help needed In the program Fill the Add statements.pdfJava Question  help needed In the program Fill the Add statements.pdf
Java Question help needed In the program Fill the Add statements.pdf
 
A topology of memory leaks on the JVM
A topology of memory leaks on the JVMA topology of memory leaks on the JVM
A topology of memory leaks on the JVM
 
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
 
hi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdfhi i have to write a java program involving link lists. i have a pro.pdf
hi i have to write a java program involving link lists. i have a pro.pdf
 
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdfCreat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
Creat Shape classes from scratch DETAILS You will create 3 shape cla.pdf
 
Please help write BinaryTree-java Thank you! Create a class BinaryTr.pdf
Please help write BinaryTree-java Thank you!   Create a class BinaryTr.pdfPlease help write BinaryTree-java Thank you!   Create a class BinaryTr.pdf
Please help write BinaryTree-java Thank you! Create a class BinaryTr.pdf
 
I need to adjust this Huffman code so that it asks for the user to i.pdf
I need to adjust this Huffman code so that it asks for the user to i.pdfI need to adjust this Huffman code so that it asks for the user to i.pdf
I need to adjust this Huffman code so that it asks for the user to i.pdf
 
usingpackage util;import java.util.;This class implements.pdf
usingpackage util;import java.util.;This class implements.pdfusingpackage util;import java.util.;This class implements.pdf
usingpackage util;import java.util.;This class implements.pdf
 
Csharp In Detail Part2
Csharp In Detail Part2Csharp In Detail Part2
Csharp In Detail Part2
 

More from arjuncorner565

Write about Participatory Design Issues and Concerns (use your own.pdf
Write about Participatory Design Issues and Concerns (use your own.pdfWrite about Participatory Design Issues and Concerns (use your own.pdf
Write about Participatory Design Issues and Concerns (use your own.pdfarjuncorner565
 
Why do some vertebrates, like a hellbender salamander, exchange oxyg.pdf
Why do some vertebrates, like a hellbender salamander, exchange oxyg.pdfWhy do some vertebrates, like a hellbender salamander, exchange oxyg.pdf
Why do some vertebrates, like a hellbender salamander, exchange oxyg.pdfarjuncorner565
 
Which of the following is the most direct source of energy for cotran.pdf
Which of the following is the most direct source of energy for cotran.pdfWhich of the following is the most direct source of energy for cotran.pdf
Which of the following is the most direct source of energy for cotran.pdfarjuncorner565
 
Which minerals commonly show pleochroisma. Isometric minerals.pdf
Which minerals commonly show pleochroisma. Isometric minerals.pdfWhich minerals commonly show pleochroisma. Isometric minerals.pdf
Which minerals commonly show pleochroisma. Isometric minerals.pdfarjuncorner565
 
Two cards are drawn from a standard deck of cards. Determine the pro.pdf
Two cards are drawn from a standard deck of cards. Determine the pro.pdfTwo cards are drawn from a standard deck of cards. Determine the pro.pdf
Two cards are drawn from a standard deck of cards. Determine the pro.pdfarjuncorner565
 
The probability that a student will find a (desirable) job before gr.pdf
The probability that a student will find a (desirable) job before gr.pdfThe probability that a student will find a (desirable) job before gr.pdf
The probability that a student will find a (desirable) job before gr.pdfarjuncorner565
 
The Northern Pacific Railroad actively lobbied for which of the foll.pdf
The Northern Pacific Railroad actively lobbied for which of the foll.pdfThe Northern Pacific Railroad actively lobbied for which of the foll.pdf
The Northern Pacific Railroad actively lobbied for which of the foll.pdfarjuncorner565
 
The difference between vertical and horizontal transmission of plant .pdf
The difference between vertical and horizontal transmission of plant .pdfThe difference between vertical and horizontal transmission of plant .pdf
The difference between vertical and horizontal transmission of plant .pdfarjuncorner565
 
select all that apply to ground substanceSolutionLets us see w.pdf
select all that apply to ground substanceSolutionLets us see w.pdfselect all that apply to ground substanceSolutionLets us see w.pdf
select all that apply to ground substanceSolutionLets us see w.pdfarjuncorner565
 
Relying on the above pathway for biosynthesis of tryptophan, fill i.pdf
Relying on the above pathway for biosynthesis of tryptophan, fill i.pdfRelying on the above pathway for biosynthesis of tryptophan, fill i.pdf
Relying on the above pathway for biosynthesis of tryptophan, fill i.pdfarjuncorner565
 
Question 7 (2 points)A researcher conducts a study on the realtion.pdf
Question 7 (2 points)A researcher conducts a study on the realtion.pdfQuestion 7 (2 points)A researcher conducts a study on the realtion.pdf
Question 7 (2 points)A researcher conducts a study on the realtion.pdfarjuncorner565
 
Primary difference between the income sections for form 1120 and .pdf
Primary difference between the income sections for form 1120 and .pdfPrimary difference between the income sections for form 1120 and .pdf
Primary difference between the income sections for form 1120 and .pdfarjuncorner565
 
Once its readable i will be okay.SolutionI will be okay in.pdf
Once its readable i will be okay.SolutionI will be okay in.pdfOnce its readable i will be okay.SolutionI will be okay in.pdf
Once its readable i will be okay.SolutionI will be okay in.pdfarjuncorner565
 
Need the mutiple choice answered uslde .An)_can omunicate with a sys.pdf
Need the mutiple choice answered uslde .An)_can omunicate with a sys.pdfNeed the mutiple choice answered uslde .An)_can omunicate with a sys.pdf
Need the mutiple choice answered uslde .An)_can omunicate with a sys.pdfarjuncorner565
 
Need a strong biologistgeneticist to answer this P element question.pdf
Need a strong biologistgeneticist to answer this P element question.pdfNeed a strong biologistgeneticist to answer this P element question.pdf
Need a strong biologistgeneticist to answer this P element question.pdfarjuncorner565
 
Listed are 2 of the core theories of evolution. For each, give a def.pdf
Listed are 2 of the core theories of evolution. For each, give a def.pdfListed are 2 of the core theories of evolution. For each, give a def.pdf
Listed are 2 of the core theories of evolution. For each, give a def.pdfarjuncorner565
 
Light is confined within the core of a simple clad optical fiber by.pdf
Light is confined within the core of a simple clad optical fiber by.pdfLight is confined within the core of a simple clad optical fiber by.pdf
Light is confined within the core of a simple clad optical fiber by.pdfarjuncorner565
 
Let L R^n rightarrow R^m be a linear transformation. Show that if n .pdf
Let L R^n rightarrow R^m be a linear transformation. Show that if n .pdfLet L R^n rightarrow R^m be a linear transformation. Show that if n .pdf
Let L R^n rightarrow R^m be a linear transformation. Show that if n .pdfarjuncorner565
 
IS path vector routing algorithm closer to the distance vector rou.pdf
IS path vector routing algorithm closer to the distance vector rou.pdfIS path vector routing algorithm closer to the distance vector rou.pdf
IS path vector routing algorithm closer to the distance vector rou.pdfarjuncorner565
 
a growth medium that can determine if a bacterium contains several d.pdf
a growth medium that can determine if a bacterium contains several d.pdfa growth medium that can determine if a bacterium contains several d.pdf
a growth medium that can determine if a bacterium contains several d.pdfarjuncorner565
 

More from arjuncorner565 (20)

Write about Participatory Design Issues and Concerns (use your own.pdf
Write about Participatory Design Issues and Concerns (use your own.pdfWrite about Participatory Design Issues and Concerns (use your own.pdf
Write about Participatory Design Issues and Concerns (use your own.pdf
 
Why do some vertebrates, like a hellbender salamander, exchange oxyg.pdf
Why do some vertebrates, like a hellbender salamander, exchange oxyg.pdfWhy do some vertebrates, like a hellbender salamander, exchange oxyg.pdf
Why do some vertebrates, like a hellbender salamander, exchange oxyg.pdf
 
Which of the following is the most direct source of energy for cotran.pdf
Which of the following is the most direct source of energy for cotran.pdfWhich of the following is the most direct source of energy for cotran.pdf
Which of the following is the most direct source of energy for cotran.pdf
 
Which minerals commonly show pleochroisma. Isometric minerals.pdf
Which minerals commonly show pleochroisma. Isometric minerals.pdfWhich minerals commonly show pleochroisma. Isometric minerals.pdf
Which minerals commonly show pleochroisma. Isometric minerals.pdf
 
Two cards are drawn from a standard deck of cards. Determine the pro.pdf
Two cards are drawn from a standard deck of cards. Determine the pro.pdfTwo cards are drawn from a standard deck of cards. Determine the pro.pdf
Two cards are drawn from a standard deck of cards. Determine the pro.pdf
 
The probability that a student will find a (desirable) job before gr.pdf
The probability that a student will find a (desirable) job before gr.pdfThe probability that a student will find a (desirable) job before gr.pdf
The probability that a student will find a (desirable) job before gr.pdf
 
The Northern Pacific Railroad actively lobbied for which of the foll.pdf
The Northern Pacific Railroad actively lobbied for which of the foll.pdfThe Northern Pacific Railroad actively lobbied for which of the foll.pdf
The Northern Pacific Railroad actively lobbied for which of the foll.pdf
 
The difference between vertical and horizontal transmission of plant .pdf
The difference between vertical and horizontal transmission of plant .pdfThe difference between vertical and horizontal transmission of plant .pdf
The difference between vertical and horizontal transmission of plant .pdf
 
select all that apply to ground substanceSolutionLets us see w.pdf
select all that apply to ground substanceSolutionLets us see w.pdfselect all that apply to ground substanceSolutionLets us see w.pdf
select all that apply to ground substanceSolutionLets us see w.pdf
 
Relying on the above pathway for biosynthesis of tryptophan, fill i.pdf
Relying on the above pathway for biosynthesis of tryptophan, fill i.pdfRelying on the above pathway for biosynthesis of tryptophan, fill i.pdf
Relying on the above pathway for biosynthesis of tryptophan, fill i.pdf
 
Question 7 (2 points)A researcher conducts a study on the realtion.pdf
Question 7 (2 points)A researcher conducts a study on the realtion.pdfQuestion 7 (2 points)A researcher conducts a study on the realtion.pdf
Question 7 (2 points)A researcher conducts a study on the realtion.pdf
 
Primary difference between the income sections for form 1120 and .pdf
Primary difference between the income sections for form 1120 and .pdfPrimary difference between the income sections for form 1120 and .pdf
Primary difference between the income sections for form 1120 and .pdf
 
Once its readable i will be okay.SolutionI will be okay in.pdf
Once its readable i will be okay.SolutionI will be okay in.pdfOnce its readable i will be okay.SolutionI will be okay in.pdf
Once its readable i will be okay.SolutionI will be okay in.pdf
 
Need the mutiple choice answered uslde .An)_can omunicate with a sys.pdf
Need the mutiple choice answered uslde .An)_can omunicate with a sys.pdfNeed the mutiple choice answered uslde .An)_can omunicate with a sys.pdf
Need the mutiple choice answered uslde .An)_can omunicate with a sys.pdf
 
Need a strong biologistgeneticist to answer this P element question.pdf
Need a strong biologistgeneticist to answer this P element question.pdfNeed a strong biologistgeneticist to answer this P element question.pdf
Need a strong biologistgeneticist to answer this P element question.pdf
 
Listed are 2 of the core theories of evolution. For each, give a def.pdf
Listed are 2 of the core theories of evolution. For each, give a def.pdfListed are 2 of the core theories of evolution. For each, give a def.pdf
Listed are 2 of the core theories of evolution. For each, give a def.pdf
 
Light is confined within the core of a simple clad optical fiber by.pdf
Light is confined within the core of a simple clad optical fiber by.pdfLight is confined within the core of a simple clad optical fiber by.pdf
Light is confined within the core of a simple clad optical fiber by.pdf
 
Let L R^n rightarrow R^m be a linear transformation. Show that if n .pdf
Let L R^n rightarrow R^m be a linear transformation. Show that if n .pdfLet L R^n rightarrow R^m be a linear transformation. Show that if n .pdf
Let L R^n rightarrow R^m be a linear transformation. Show that if n .pdf
 
IS path vector routing algorithm closer to the distance vector rou.pdf
IS path vector routing algorithm closer to the distance vector rou.pdfIS path vector routing algorithm closer to the distance vector rou.pdf
IS path vector routing algorithm closer to the distance vector rou.pdf
 
a growth medium that can determine if a bacterium contains several d.pdf
a growth medium that can determine if a bacterium contains several d.pdfa growth medium that can determine if a bacterium contains several d.pdf
a growth medium that can determine if a bacterium contains several d.pdf
 

Recently uploaded

Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfadityarao40181
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxUnboundStockton
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfSumit Tiwari
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsKarinaGenton
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaVirag Sontakke
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxAvyJaneVismanos
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting DataJhengPantaleon
 
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
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxsocialsciencegdgrohi
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxGaneshChakor2
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonJericReyAuditor
 
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
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdfSoniaTolstoy
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfsanyamsingh5019
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerunnathinaik
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Sapana Sha
 
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
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxiammrhaywood
 

Recently uploaded (20)

Biting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdfBiting mechanism of poisonous snakes.pdf
Biting mechanism of poisonous snakes.pdf
 
Blooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docxBlooming Together_ Growing a Community Garden Worksheet.docx
Blooming Together_ Growing a Community Garden Worksheet.docx
 
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdfEnzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
Enzyme, Pharmaceutical Aids, Miscellaneous Last Part of Chapter no 5th.pdf
 
Science 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its CharacteristicsScience 7 - LAND and SEA BREEZE and its Characteristics
Science 7 - LAND and SEA BREEZE and its Characteristics
 
Painted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of IndiaPainted Grey Ware.pptx, PGW Culture of India
Painted Grey Ware.pptx, PGW Culture of India
 
Final demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptxFinal demo Grade 9 for demo Plan dessert.pptx
Final demo Grade 9 for demo Plan dessert.pptx
 
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data_Math 4-Q4 Week 5.pptx Steps in Collecting Data
_Math 4-Q4 Week 5.pptx Steps in Collecting Data
 
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
Model Call Girl in Tilak Nagar Delhi reach out to us at 🔝9953056974🔝
 
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
 
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptxHistory Class XII Ch. 3 Kinship, Caste and Class (1).pptx
History Class XII Ch. 3 Kinship, Caste and Class (1).pptx
 
CARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptxCARE OF CHILD IN INCUBATOR..........pptx
CARE OF CHILD IN INCUBATOR..........pptx
 
Science lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lessonScience lesson Moon for 4th quarter lesson
Science lesson Moon for 4th quarter lesson
 
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
 
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdfBASLIQ CURRENT LOOKBOOK  LOOKBOOK(1) (1).pdf
BASLIQ CURRENT LOOKBOOK LOOKBOOK(1) (1).pdf
 
Sanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdfSanyam Choudhary Chemistry practical.pdf
Sanyam Choudhary Chemistry practical.pdf
 
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
 
internship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developerinternship ppt on smartinternz platform as salesforce developer
internship ppt on smartinternz platform as salesforce developer
 
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111Call Girls in Dwarka Mor Delhi Contact Us 9654467111
Call Girls in Dwarka Mor Delhi Contact Us 9654467111
 
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
 
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptxSOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
SOCIAL AND HISTORICAL CONTEXT - LFTVD.pptx
 

Modify HuffmanTree.java and HuffmanNode.java to allow the user to se.pdf

  • 1. Modify HuffmanTree.java and HuffmanNode.java to allow the user to select the value of n 9 to construct an n ary Huffman Tree. Once finished, verify the accuracy of your tree by running it for the English Alphabet for n = 3, 4, 5, 6, 7, 8, 9. For each value of n, compute the average codeword length. Write these in a table (n vs. ACW L(Cn)). / HuffmanTree.java import java.io.FileNotFoundException; import java.io.FileReader; import java.util.ArrayList; import java.util.Scanner; public class HuffmanTree { public static void main(String[] args){ Scanner in = new Scanner(System.in); System.out.print("Enter the file name: "); String fileName = in.nextLine(); ArrayList nodes = new ArrayList<>(); ArrayList temp = new ArrayList<>(); try { Scanner fin = new Scanner(new FileReader(fileName)); String symbol; double prob; while(fin.hasNext()){ symbol = fin.next(); prob = fin.nextDouble(); nodes.add(findInsertIndex(nodes, prob), new HuffmanNode(symbol, prob)); } fin.close(); temp.addAll(nodes); HuffmanNode root = createHuffmanTree(temp); setCodeWords(root); double avg = 0; for (HuffmanNode node : nodes) { System.out.println(node.getS() + ": " + node.getC() + ": " + node.getL()); avg += node.getL();
  • 2. } if(avg != 0) avg /= nodes.size(); System.out.println("Average code length is: " + avg); } catch (FileNotFoundException e) { e.printStackTrace(); } } private static HuffmanNode createHuffmanTree(ArrayList nodes){ HuffmanNode root = null; if(nodes.size() > 0) { HuffmanNode node0, node1, node; while (nodes.size() > 1) { node0 = nodes.get(0); node1 = nodes.get(1); node = new HuffmanNode(null, node0.getP() + node1.getP()); node.setLeft(node0); node.setRight(node1); nodes.remove(0); nodes.remove(0); nodes.add(findInsertIndex(nodes, node.getP()), node); } root = nodes.get(0); } return root; } private static void setCodeWords(HuffmanNode root){ if(root != null){ setCodeWords(root, ""); } } private static void setCodeWords(HuffmanNode root, String codeWord){ if(root.getS() != null){
  • 3. root.setC(codeWord); root.setL(codeWord.length()); } else{ setCodeWords(root.getLeft(), codeWord + "0"); setCodeWords(root.getRight(), codeWord + "1"); } } private static int findInsertIndex(ArrayList nodes, double prob){ for(int i = 0; i < nodes.size(); ++i){ if(prob < nodes.get(i).getP()){ return i; } } return nodes.size(); } } // HuffmanNode.java public class HuffmanNode { private String S; private double P; private String C; private int L; private HuffmanNode left, right; public HuffmanNode(String s, double p) { S = s; P = p; } public String getS() { return S; }
  • 4. public void setS(String s) { S = s; } public double getP() { return P; } public void setP(double p) { P = p; } public String getC() { return C; } public void setC(String c) { C = c; } public int getL() { return L; } public void setL(int l) { L = l; } public HuffmanNode getLeft() { return left; } public void setLeft(HuffmanNode left) { this.left = left; }
  • 5. public HuffmanNode getRight() { return right; } public void setRight(HuffmanNode right) { this.right = right; } } //EnglishAlphabet.txt (symbols with probability) Solution public final class Huffman { private Huffman() {}; private static class HuffmanNode { char ch; int frequency; HuffmanNode left; HuffmanNode right; HuffmanNode(char ch, int frequency, HuffmanNode left, HuffmanNode right) { this.ch = ch; this.frequency = frequency; this.left = left; this.right = right; } } private static class HuffManComparator implements Comparator { @Override public int compare(HuffmanNode node1, HuffmanNode node2) { return node1.frequency - node2.frequency; } } /** * Compresses the string using huffman algorithm. * The huffman tree and the huffman code are serialized to disk * * @param sentence The sentence to be serialized * @throws FileNotFoundException If file is not found * @throws IOException If IO exception occurs. */ public static void compress(String sentence) throws FileNotFoundException, IOException { if (sentence == null) { throw new NullPointerException("Input sentence cannot be null."); } if (sentence.length() == 0) { throw new IllegalArgumentException("The string should atleast have 1 character."); } final Map charFreq = getCharFrequency(sentence); final HuffmanNode root = buildTree(charFreq); final Map charCode = generateCodes(charFreq.keySet(), root); final String encodedMessage = encodeMessage(charCode, sentence); serializeTree(root); serializeMessage(encodedMessage); } private static Map getCharFrequency(String sentence) { final Map map = new HashMap(); for (int i = 0; i < sentence.length(); i++) { char ch = sentence.charAt(i); if (!map.containsKey(ch)) { map.put(ch, 1); } else { int val = map.get(ch); map.put(ch, ++val); } } return map; } /** * Map map * Some implementation of that treeSet is passed as parameter. * @param map */ private static HuffmanNode buildTree(Map map) { final Queue nodeQueue = createNodeQueue(map); while (nodeQueue.size() > 1) {
  • 6. final HuffmanNode node1 = nodeQueue.remove(); final HuffmanNode node2 = nodeQueue.remove(); HuffmanNode node = new HuffmanNode('0', node1.frequency + node2.frequency, node1, node2); nodeQueue.add(node); } // remove it to prevent object leak. return nodeQueue.remove(); } private static Queue createNodeQueue(Map map) { final Queue pq = new PriorityQueue(11, new HuffManComparator()); for (Entry entry : map.entrySet()) { pq.add(new HuffmanNode(entry.getKey(), entry.getValue(), null, null)); } return pq; } private static Map generateCodes(Set chars, HuffmanNode node) { final Map map = new HashMap(); doGenerateCode(node, map, ""); return map; } private static void doGenerateCode(HuffmanNode node, Map map, String s) { if (node.left == null && node.right == null) { map.put(node.ch, s); return; } doGenerateCode(node.left, map, s + '0'); doGenerateCode(node.right, map, s + '1' ); } private static String encodeMessage(Map charCode, String sentence) { final StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < sentence.length(); i++) { stringBuilder.append(charCode.get(sentence.charAt(i))); } return stringBuilder.toString(); } private static void serializeTree(HuffmanNode node) throws FileNotFoundException, IOException { final BitSet bitSet = new BitSet(); try (ObjectOutputStream oosTree = new ObjectOutputStream(new FileOutputStream("/Users/ap/Desktop/tree"))) { try (ObjectOutputStream oosChar = new ObjectOutputStream(new FileOutputStream("/Users/ap/Desktop/char"))) { IntObject o = new IntObject(); preOrder(node, oosChar, bitSet, o); bitSet.set(o.bitPosition, true); // padded to mark end of bit set relevant for deserialization. oosTree.writeObject(bitSet); } } } private static class IntObject { int bitPosition; } /* * Algo: * 1. Access the node * 2. Register the value in bit set. * * * here true and false dont correspond to left branch and right branch. * there, * - true means "a branch originates from leaf" * - false mens "a branch originates from non- left". * * Also since branches originate from some node, the root node must be provided as source * or starting point of initial branches. * * Diagram and how an bit set would look as a result. * (source node) * / * true true * / * (leaf node) (leaf node) * | | * false false * | | * * So now a bit set looks like [false, true, false, true] * */ private static void preOrder(HuffmanNode node, ObjectOutputStream oosChar, BitSet bitSet, IntObject intObject) throws IOException { if (node.left == null && node.right == null) { bitSet.set(intObject.bitPosition++, false); // register branch in bitset oosChar.writeChar(node.ch); return; // DONT take the branch. } bitSet.set(intObject.bitPosition++, true); // register
  • 7. branch in bitset preOrder(node.left, oosChar, bitSet, intObject); // take the branch. bitSet.set(intObject.bitPosition++, true); // register branch in bitset preOrder(node.right, oosChar, bitSet, intObject); // take the branch. } private static void serializeMessage(String message) throws IOException { final BitSet bitSet = getBitSet(message); try (ObjectOutputStream oos = new ObjectOutputStream(new FileOutputStream("/Users/ap/Desktop/encodedMessage"))){ oos.writeObject(bitSet); } } private static BitSet getBitSet(String message) { final BitSet bitSet = new BitSet(); int i = 0; for (i = 0; i < message.length(); i++) { if (message.charAt(i) == '0') { bitSet.set(i, false); } else { bitSet.set(i, true); } } bitSet.set(i, true); // dummy bit set to know the length return bitSet; } /** * Retrieves back the original string. * * * @return The original uncompressed string * @throws FileNotFoundException If the file is not found * @throws ClassNotFoundException If class is not found * @throws IOException If IOException occurs */ public static String expand() throws FileNotFoundException, ClassNotFoundException, IOException { final HuffmanNode root = deserializeTree(); return decodeMessage(root); } private static HuffmanNode deserializeTree() throws FileNotFoundException, IOException, ClassNotFoundException { try (ObjectInputStream oisBranch = new ObjectInputStream(new FileInputStream("/Users/ap/Desktop/tree"))) { try (ObjectInputStream oisChar = new ObjectInputStream(new FileInputStream("/Users/ap/Desktop/char"))) { final BitSet bitSet = (BitSet) oisBranch.readObject(); return preOrder(bitSet, oisChar, new IntObject()); } } } /* * Construct a tree from: * input [false, true, false, true, (dummy true to mark the end of bit set)] * The input is constructed from preorder traversal * * Algo: * 1 Create the node. * 2. Read what is registered in bitset, and decide if created node is supposed to be a leaf or non-leaf * */ private static HuffmanNode preOrder(BitSet bitSet, ObjectInputStream oisChar, IntObject o) throws IOException { // created the node before reading whats registered. final HuffmanNode node = new HuffmanNode('0', 0, null, null); // reading whats registered and determining if created node is the leaf or non-leaf. if (!bitSet.get(o.bitPosition)) { o.bitPosition++; // feed the next position to the next stack frame by doing computation before preOrder is called. node.ch = oisChar.readChar(); return node; } o.bitPosition = o.bitPosition + 1; // feed the next position to the next stack frame by doing computation before preOrder is called. node.left = preOrder(bitSet, oisChar, o); o.bitPosition = o.bitPosition + 1; // feed the next position to the next stack frame by doing computation before preOrder is called. node.right = preOrder(bitSet, oisChar, o); return node; } private static String decodeMessage(HuffmanNode node) throws FileNotFoundException, IOException,
  • 8. ClassNotFoundException { try (ObjectInputStream ois = new ObjectInputStream(new FileInputStream("/Users/ameya.patil/Desktop/encodedMessage"))) { final BitSet bitSet = (BitSet) ois.readObject(); final StringBuilder stringBuilder = new StringBuilder(); for (int i = 0; i < (bitSet.length() - 1);) { HuffmanNode temp = node; // since huffman code generates full binary tree, temp.right is certainly null if temp.left is null. while (temp.left != null) { if (!bitSet.get(i)) { temp = temp.left; } else { temp = temp.right; } i = i + 1; } stringBuilder.append(temp.ch); } return stringBuilder.toString(); } } public static void main(String[] args) throws FileNotFoundException, IOException, ClassNotFoundException { // even number of characters Huffman.compress("some"); Assert.assertEquals("some", Huffman.expand()); // odd number of characters Huffman.compress("someday"); Assert.assertEquals("someday", Huffman.expand()); // repeating even number of characters + space + non-ascii Huffman.compress("some some#"); Assert.assertEquals("some some#", Huffman.expand()); // odd number of characters + space + non-ascii Huffman.compress("someday someday&"); Assert.assertEquals("someday someday&", Huffman.expand()); } }