SlideShare a Scribd company logo
1 of 7
Download to read offline
write a java program related to Huffman coding.
Solution
The Java program for Huffman coding is as below:
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;
}
}
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;
}
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);
}
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);
oosTree.writeObject(bitSet);
}
}
}
private static class IntObject
{
int bitPosition;
}
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);
oosChar.writeChar(node.ch);
return;
}
bitSet.set(intObject.bitPosition++, true);
preOrder(node.left, oosChar, bitSet, intObject);
bitSet.set(intObject.bitPosition++, true);
preOrder(node.right, oosChar, bitSet, intObject);
}
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);
return bitSet;
}
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());
}
}
}
private static HuffmanNode preOrder(BitSet bitSet, ObjectInputStream oisChar, IntObject o)
throws IOException {
final HuffmanNode node = new HuffmanNode('0', 0, null, null);
if (!bitSet.get(o.bitPosition)) {
o.bitPosition++;
node.ch = oisChar.readChar();
return node;
}
o.bitPosition = o.bitPosition + 1;
node.left = preOrder(bitSet, oisChar, o);
o.bitPosition = o.bitPosition + 1;
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;
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 {
Huffman.compress("some");
Assert.assertEquals("some", Huffman.expand());
Huffman.compress("someday");
Assert.assertEquals("someday", Huffman.expand());
Huffman.compress("some some#");
Assert.assertEquals("some some#", Huffman.expand());
Huffman.compress("someday someday&");
Assert.assertEquals("someday someday&", Huffman.expand());
}
}

More Related Content

Similar to write a java program related to Huffman coding.SolutionThe Jav.pdf

soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch
 
Need help with this paperThis assignment consists of writing resea.pdf
Need help with this paperThis assignment consists of writing resea.pdfNeed help with this paperThis assignment consists of writing resea.pdf
Need help with this paperThis assignment consists of writing resea.pdfsktambifortune
 
Voxxed Days Vilnius 2015 - Having fun with Javassist
Voxxed Days Vilnius 2015 - Having fun with JavassistVoxxed Days Vilnius 2015 - Having fun with Javassist
Voxxed Days Vilnius 2015 - Having fun with JavassistAnton Arhipov
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript IntroductionDmitry Sheiko
 
JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistAnton Arhipov
 
Tips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET ApplicationTips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET ApplicationJoni
 
JavaSE7 Launch Event: Java7xGroovy
JavaSE7 Launch Event: Java7xGroovyJavaSE7 Launch Event: Java7xGroovy
JavaSE7 Launch Event: Java7xGroovyYasuharu Nakano
 
5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системеDEVTYPE
 
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
 
What’s new in C# 6
What’s new in C# 6What’s new in C# 6
What’s new in C# 6Fiyaz Hasan
 
Objective Min-heap queue with customized comparatorHospital emerg.pdf
Objective Min-heap queue with customized comparatorHospital emerg.pdfObjective Min-heap queue with customized comparatorHospital emerg.pdf
Objective Min-heap queue with customized comparatorHospital emerg.pdfezhilvizhiyan
 
20070329 Java Programing Tips
20070329 Java Programing Tips20070329 Java Programing Tips
20070329 Java Programing TipsShingo Furuyama
 
Implement threads and a GUI interface using advanced Java Swing clas.pdf
Implement threads and a GUI interface using advanced Java Swing clas.pdfImplement threads and a GUI interface using advanced Java Swing clas.pdf
Implement threads and a GUI interface using advanced Java Swing clas.pdfamrishinda
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming iiPrashant Kalkar
 

Similar to write a java program related to Huffman coding.SolutionThe Jav.pdf (20)

Java 7 LavaJUG
Java 7 LavaJUGJava 7 LavaJUG
Java 7 LavaJUG
 
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coinsoft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
soft-shake.ch - Java SE 7: The Fork/Join Framework and Project Coin
 
Need help with this paperThis assignment consists of writing resea.pdf
Need help with this paperThis assignment consists of writing resea.pdfNeed help with this paperThis assignment consists of writing resea.pdf
Need help with this paperThis assignment consists of writing resea.pdf
 
Voxxed Days Vilnius 2015 - Having fun with Javassist
Voxxed Days Vilnius 2015 - Having fun with JavassistVoxxed Days Vilnius 2015 - Having fun with Javassist
Voxxed Days Vilnius 2015 - Having fun with Javassist
 
TypeScript Introduction
TypeScript IntroductionTypeScript Introduction
TypeScript Introduction
 
JEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with JavassistJEEConf 2017 - Having fun with Javassist
JEEConf 2017 - Having fun with Javassist
 
Tips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET ApplicationTips and Tricks of Developing .NET Application
Tips and Tricks of Developing .NET Application
 
PathOfMostResistance
PathOfMostResistancePathOfMostResistance
PathOfMostResistance
 
JavaSE7 Launch Event: Java7xGroovy
JavaSE7 Launch Event: Java7xGroovyJavaSE7 Launch Event: Java7xGroovy
JavaSE7 Launch Event: Java7xGroovy
 
5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе5. Ввод-вывод, доступ к файловой системе
5. Ввод-вывод, доступ к файловой системе
 
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# 6
What’s new in C# 6What’s new in C# 6
What’s new in C# 6
 
Objective Min-heap queue with customized comparatorHospital emerg.pdf
Objective Min-heap queue with customized comparatorHospital emerg.pdfObjective Min-heap queue with customized comparatorHospital emerg.pdf
Objective Min-heap queue with customized comparatorHospital emerg.pdf
 
Inheritance
InheritanceInheritance
Inheritance
 
20070329 Java Programing Tips
20070329 Java Programing Tips20070329 Java Programing Tips
20070329 Java Programing Tips
 
Implement threads and a GUI interface using advanced Java Swing clas.pdf
Implement threads and a GUI interface using advanced Java Swing clas.pdfImplement threads and a GUI interface using advanced Java Swing clas.pdf
Implement threads and a GUI interface using advanced Java Swing clas.pdf
 
Lezione03
Lezione03Lezione03
Lezione03
 
Lezione03
Lezione03Lezione03
Lezione03
 
Functional programming ii
Functional programming iiFunctional programming ii
Functional programming ii
 
Scala in practice
Scala in practiceScala in practice
Scala in practice
 

More from jaronkyleigh59760

Determine whether the following scenarios is a permutation or a comb.pdf
Determine whether the following scenarios is a permutation or a comb.pdfDetermine whether the following scenarios is a permutation or a comb.pdf
Determine whether the following scenarios is a permutation or a comb.pdfjaronkyleigh59760
 
Define the Replacement Model (complete and partial)Define the Mul.pdf
Define the Replacement Model (complete and partial)Define the Mul.pdfDefine the Replacement Model (complete and partial)Define the Mul.pdf
Define the Replacement Model (complete and partial)Define the Mul.pdfjaronkyleigh59760
 
Create the Java function to receive an ArrayList object. The functio.pdf
Create the Java function to receive an ArrayList object. The functio.pdfCreate the Java function to receive an ArrayList object. The functio.pdf
Create the Java function to receive an ArrayList object. The functio.pdfjaronkyleigh59760
 
ancestral gene Map speciation 1 Similarly colored genes designate gen.pdf
ancestral gene Map speciation 1 Similarly colored genes designate gen.pdfancestral gene Map speciation 1 Similarly colored genes designate gen.pdf
ancestral gene Map speciation 1 Similarly colored genes designate gen.pdfjaronkyleigh59760
 
A red blood cell enters the right common iliac artery. In order, list.pdf
A red blood cell enters the right common iliac artery. In order, list.pdfA red blood cell enters the right common iliac artery. In order, list.pdf
A red blood cell enters the right common iliac artery. In order, list.pdfjaronkyleigh59760
 
Contrast the following types of remote attacks virus, worm, phishin.pdf
Contrast the following types of remote attacks virus, worm, phishin.pdfContrast the following types of remote attacks virus, worm, phishin.pdf
Contrast the following types of remote attacks virus, worm, phishin.pdfjaronkyleigh59760
 
17. Unnithan, Houser, and Fernhall (2006) were interested in whether.pdf
17. Unnithan, Houser, and Fernhall (2006) were interested in whether.pdf17. Unnithan, Houser, and Fernhall (2006) were interested in whether.pdf
17. Unnithan, Houser, and Fernhall (2006) were interested in whether.pdfjaronkyleigh59760
 
Review Questions 5.1 5.2 5.3 5.4 5.5 5.6 What is transmission Distin.pdf
Review Questions 5.1 5.2 5.3 5.4 5.5 5.6 What is transmission Distin.pdfReview Questions 5.1 5.2 5.3 5.4 5.5 5.6 What is transmission Distin.pdf
Review Questions 5.1 5.2 5.3 5.4 5.5 5.6 What is transmission Distin.pdfjaronkyleigh59760
 
Why do ion channels not function like open poresWhat is membrane .pdf
Why do ion channels not function like open poresWhat is membrane .pdfWhy do ion channels not function like open poresWhat is membrane .pdf
Why do ion channels not function like open poresWhat is membrane .pdfjaronkyleigh59760
 
Which of the following is not an organic molecule C_12 H_9 SO_3.pdf
Which of the following is not an organic molecule  C_12 H_9 SO_3.pdfWhich of the following is not an organic molecule  C_12 H_9 SO_3.pdf
Which of the following is not an organic molecule C_12 H_9 SO_3.pdfjaronkyleigh59760
 
1. The process of an internal employee or outside consultant reviewi.pdf
1. The process of an internal employee or outside consultant reviewi.pdf1. The process of an internal employee or outside consultant reviewi.pdf
1. The process of an internal employee or outside consultant reviewi.pdfjaronkyleigh59760
 
what does the pi signify in statistics I have a Ho and Ha. pi(i.pdf
what does the pi signify in statistics I have a Ho and Ha. pi(i.pdfwhat does the pi signify in statistics I have a Ho and Ha. pi(i.pdf
what does the pi signify in statistics I have a Ho and Ha. pi(i.pdfjaronkyleigh59760
 
what are the changes to IMC strategy a company faces in light of the.pdf
what are the changes to IMC strategy a company faces in light of the.pdfwhat are the changes to IMC strategy a company faces in light of the.pdf
what are the changes to IMC strategy a company faces in light of the.pdfjaronkyleigh59760
 
What factors did the researchers determine prevented the Soay sheep i.pdf
What factors did the researchers determine prevented the Soay sheep i.pdfWhat factors did the researchers determine prevented the Soay sheep i.pdf
What factors did the researchers determine prevented the Soay sheep i.pdfjaronkyleigh59760
 
What are homologous traits Similar traits in different organisms bas.pdf
What are homologous traits Similar traits in different organisms bas.pdfWhat are homologous traits Similar traits in different organisms bas.pdf
What are homologous traits Similar traits in different organisms bas.pdfjaronkyleigh59760
 
There are 102 people consisting of 51 married couples in a room. Ass.pdf
There are 102 people consisting of 51 married couples in a room. Ass.pdfThere are 102 people consisting of 51 married couples in a room. Ass.pdf
There are 102 people consisting of 51 married couples in a room. Ass.pdfjaronkyleigh59760
 
List the necessary steps for the Abiotic origin of life theoryS.pdf
List the necessary steps for the Abiotic origin of life theoryS.pdfList the necessary steps for the Abiotic origin of life theoryS.pdf
List the necessary steps for the Abiotic origin of life theoryS.pdfjaronkyleigh59760
 
ldentify the correct statement(s) regarding threats to independence .pdf
ldentify the correct statement(s) regarding threats to independence .pdfldentify the correct statement(s) regarding threats to independence .pdf
ldentify the correct statement(s) regarding threats to independence .pdfjaronkyleigh59760
 
Item 1In the case below, the original source material is given alo.pdf
Item 1In the case below, the original source material is given alo.pdfItem 1In the case below, the original source material is given alo.pdf
Item 1In the case below, the original source material is given alo.pdfjaronkyleigh59760
 
In your opinion, what is the purpose of a funeral What function doe.pdf
In your opinion, what is the purpose of a funeral What function doe.pdfIn your opinion, what is the purpose of a funeral What function doe.pdf
In your opinion, what is the purpose of a funeral What function doe.pdfjaronkyleigh59760
 

More from jaronkyleigh59760 (20)

Determine whether the following scenarios is a permutation or a comb.pdf
Determine whether the following scenarios is a permutation or a comb.pdfDetermine whether the following scenarios is a permutation or a comb.pdf
Determine whether the following scenarios is a permutation or a comb.pdf
 
Define the Replacement Model (complete and partial)Define the Mul.pdf
Define the Replacement Model (complete and partial)Define the Mul.pdfDefine the Replacement Model (complete and partial)Define the Mul.pdf
Define the Replacement Model (complete and partial)Define the Mul.pdf
 
Create the Java function to receive an ArrayList object. The functio.pdf
Create the Java function to receive an ArrayList object. The functio.pdfCreate the Java function to receive an ArrayList object. The functio.pdf
Create the Java function to receive an ArrayList object. The functio.pdf
 
ancestral gene Map speciation 1 Similarly colored genes designate gen.pdf
ancestral gene Map speciation 1 Similarly colored genes designate gen.pdfancestral gene Map speciation 1 Similarly colored genes designate gen.pdf
ancestral gene Map speciation 1 Similarly colored genes designate gen.pdf
 
A red blood cell enters the right common iliac artery. In order, list.pdf
A red blood cell enters the right common iliac artery. In order, list.pdfA red blood cell enters the right common iliac artery. In order, list.pdf
A red blood cell enters the right common iliac artery. In order, list.pdf
 
Contrast the following types of remote attacks virus, worm, phishin.pdf
Contrast the following types of remote attacks virus, worm, phishin.pdfContrast the following types of remote attacks virus, worm, phishin.pdf
Contrast the following types of remote attacks virus, worm, phishin.pdf
 
17. Unnithan, Houser, and Fernhall (2006) were interested in whether.pdf
17. Unnithan, Houser, and Fernhall (2006) were interested in whether.pdf17. Unnithan, Houser, and Fernhall (2006) were interested in whether.pdf
17. Unnithan, Houser, and Fernhall (2006) were interested in whether.pdf
 
Review Questions 5.1 5.2 5.3 5.4 5.5 5.6 What is transmission Distin.pdf
Review Questions 5.1 5.2 5.3 5.4 5.5 5.6 What is transmission Distin.pdfReview Questions 5.1 5.2 5.3 5.4 5.5 5.6 What is transmission Distin.pdf
Review Questions 5.1 5.2 5.3 5.4 5.5 5.6 What is transmission Distin.pdf
 
Why do ion channels not function like open poresWhat is membrane .pdf
Why do ion channels not function like open poresWhat is membrane .pdfWhy do ion channels not function like open poresWhat is membrane .pdf
Why do ion channels not function like open poresWhat is membrane .pdf
 
Which of the following is not an organic molecule C_12 H_9 SO_3.pdf
Which of the following is not an organic molecule  C_12 H_9 SO_3.pdfWhich of the following is not an organic molecule  C_12 H_9 SO_3.pdf
Which of the following is not an organic molecule C_12 H_9 SO_3.pdf
 
1. The process of an internal employee or outside consultant reviewi.pdf
1. The process of an internal employee or outside consultant reviewi.pdf1. The process of an internal employee or outside consultant reviewi.pdf
1. The process of an internal employee or outside consultant reviewi.pdf
 
what does the pi signify in statistics I have a Ho and Ha. pi(i.pdf
what does the pi signify in statistics I have a Ho and Ha. pi(i.pdfwhat does the pi signify in statistics I have a Ho and Ha. pi(i.pdf
what does the pi signify in statistics I have a Ho and Ha. pi(i.pdf
 
what are the changes to IMC strategy a company faces in light of the.pdf
what are the changes to IMC strategy a company faces in light of the.pdfwhat are the changes to IMC strategy a company faces in light of the.pdf
what are the changes to IMC strategy a company faces in light of the.pdf
 
What factors did the researchers determine prevented the Soay sheep i.pdf
What factors did the researchers determine prevented the Soay sheep i.pdfWhat factors did the researchers determine prevented the Soay sheep i.pdf
What factors did the researchers determine prevented the Soay sheep i.pdf
 
What are homologous traits Similar traits in different organisms bas.pdf
What are homologous traits Similar traits in different organisms bas.pdfWhat are homologous traits Similar traits in different organisms bas.pdf
What are homologous traits Similar traits in different organisms bas.pdf
 
There are 102 people consisting of 51 married couples in a room. Ass.pdf
There are 102 people consisting of 51 married couples in a room. Ass.pdfThere are 102 people consisting of 51 married couples in a room. Ass.pdf
There are 102 people consisting of 51 married couples in a room. Ass.pdf
 
List the necessary steps for the Abiotic origin of life theoryS.pdf
List the necessary steps for the Abiotic origin of life theoryS.pdfList the necessary steps for the Abiotic origin of life theoryS.pdf
List the necessary steps for the Abiotic origin of life theoryS.pdf
 
ldentify the correct statement(s) regarding threats to independence .pdf
ldentify the correct statement(s) regarding threats to independence .pdfldentify the correct statement(s) regarding threats to independence .pdf
ldentify the correct statement(s) regarding threats to independence .pdf
 
Item 1In the case below, the original source material is given alo.pdf
Item 1In the case below, the original source material is given alo.pdfItem 1In the case below, the original source material is given alo.pdf
Item 1In the case below, the original source material is given alo.pdf
 
In your opinion, what is the purpose of a funeral What function doe.pdf
In your opinion, what is the purpose of a funeral What function doe.pdfIn your opinion, what is the purpose of a funeral What function doe.pdf
In your opinion, what is the purpose of a funeral What function doe.pdf
 

Recently uploaded

SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code ExamplesPeter Brusilovsky
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjMohammed Sikander
 
8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital ManagementMBA Assignment Experts
 
The Liver & Gallbladder (Anatomy & Physiology).pptx
The Liver &  Gallbladder (Anatomy & Physiology).pptxThe Liver &  Gallbladder (Anatomy & Physiology).pptx
The Liver & Gallbladder (Anatomy & Physiology).pptxVishal Singh
 
e-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopale-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi RajagopalEADTU
 
diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....Ritu480198
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...EADTU
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppCeline George
 
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMDEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMELOISARIVERA8
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文中 央社
 
Contoh Aksi Nyata Refleksi Diri ( NUR ).pdf
Contoh Aksi Nyata Refleksi Diri ( NUR ).pdfContoh Aksi Nyata Refleksi Diri ( NUR ).pdf
Contoh Aksi Nyata Refleksi Diri ( NUR ).pdfcupulin
 
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnershipsexpandedwebsite
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024Borja Sotomayor
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...Nguyen Thanh Tu Collection
 

Recently uploaded (20)

SPLICE Working Group: Reusable Code Examples
SPLICE Working Group:Reusable Code ExamplesSPLICE Working Group:Reusable Code Examples
SPLICE Working Group: Reusable Code Examples
 
Supporting Newcomer Multilingual Learners
Supporting Newcomer  Multilingual LearnersSupporting Newcomer  Multilingual Learners
Supporting Newcomer Multilingual Learners
 
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjjStl Algorithms in C++ jjjjjjjjjjjjjjjjjj
Stl Algorithms in C++ jjjjjjjjjjjjjjjjjj
 
8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management8 Tips for Effective Working Capital Management
8 Tips for Effective Working Capital Management
 
The Liver & Gallbladder (Anatomy & Physiology).pptx
The Liver &  Gallbladder (Anatomy & Physiology).pptxThe Liver &  Gallbladder (Anatomy & Physiology).pptx
The Liver & Gallbladder (Anatomy & Physiology).pptx
 
e-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopale-Sealing at EADTU by Kamakshi Rajagopal
e-Sealing at EADTU by Kamakshi Rajagopal
 
VAMOS CUIDAR DO NOSSO PLANETA! .
VAMOS CUIDAR DO NOSSO PLANETA!                    .VAMOS CUIDAR DO NOSSO PLANETA!                    .
VAMOS CUIDAR DO NOSSO PLANETA! .
 
diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....
 
OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
Transparency, Recognition and the role of eSealing - Ildiko Mazar and Koen No...
 
Improved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio AppImproved Approval Flow in Odoo 17 Studio App
Improved Approval Flow in Odoo 17 Studio App
 
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUMDEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
DEMONSTRATION LESSON IN ENGLISH 4 MATATAG CURRICULUM
 
Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"Mattingly "AI & Prompt Design: Named Entity Recognition"
Mattingly "AI & Prompt Design: Named Entity Recognition"
 
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文會考英文
 
Contoh Aksi Nyata Refleksi Diri ( NUR ).pdf
Contoh Aksi Nyata Refleksi Diri ( NUR ).pdfContoh Aksi Nyata Refleksi Diri ( NUR ).pdf
Contoh Aksi Nyata Refleksi Diri ( NUR ).pdf
 
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community PartnershipsSpring gala 2024 photo slideshow - Celebrating School-Community Partnerships
Spring gala 2024 photo slideshow - Celebrating School-Community Partnerships
 
Including Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdfIncluding Mental Health Support in Project Delivery, 14 May.pdf
Including Mental Health Support in Project Delivery, 14 May.pdf
 
UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024UChicago CMSC 23320 - The Best Commit Messages of 2024
UChicago CMSC 23320 - The Best Commit Messages of 2024
 
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
ESSENTIAL of (CS/IT/IS) class 07 (Networks)ESSENTIAL of (CS/IT/IS) class 07 (Networks)
ESSENTIAL of (CS/IT/IS) class 07 (Networks)
 
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
TỔNG HỢP HƠN 100 ĐỀ THI THỬ TỐT NGHIỆP THPT TOÁN 2024 - TỪ CÁC TRƯỜNG, TRƯỜNG...
 

write a java program related to Huffman coding.SolutionThe Jav.pdf

  • 1. write a java program related to Huffman coding. Solution The Java program for Huffman coding is as below: 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; } } public static void compress(String sentence) throws FileNotFoundException, IOException { if (sentence == null) { throw new NullPointerException("Input sentence cannot be null."); } if (sentence.length() == 0) {
  • 2. 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; } 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);
  • 3. } 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();
  • 4. 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); oosTree.writeObject(bitSet); } } } private static class IntObject { int bitPosition; } 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); oosChar.writeChar(node.ch); return; } bitSet.set(intObject.bitPosition++, true); preOrder(node.left, oosChar, bitSet, intObject); bitSet.set(intObject.bitPosition++, true); preOrder(node.right, oosChar, bitSet, intObject); } 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); } }
  • 5. 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); return bitSet; } 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()); } } } private static HuffmanNode preOrder(BitSet bitSet, ObjectInputStream oisChar, IntObject o) throws IOException { final HuffmanNode node = new HuffmanNode('0', 0, null, null); if (!bitSet.get(o.bitPosition)) { o.bitPosition++;
  • 6. node.ch = oisChar.readChar(); return node; } o.bitPosition = o.bitPosition + 1; node.left = preOrder(bitSet, oisChar, o); o.bitPosition = o.bitPosition + 1; 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; 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 { Huffman.compress("some"); Assert.assertEquals("some", Huffman.expand()); Huffman.compress("someday"); Assert.assertEquals("someday", Huffman.expand());
  • 7. Huffman.compress("some some#"); Assert.assertEquals("some some#", Huffman.expand()); Huffman.compress("someday someday&"); Assert.assertEquals("someday someday&", Huffman.expand()); } }