SlideShare a Scribd company logo
1 of 13
Download to read offline
Write a program that takes any input text and produces both a frequency table and the
corresponding Huffman code. Take approximately 360 words from any English document as
your input text. Ignore all blanks, all punctuation marks, al special symbols. Create an input file
with this input text. Construct the frequency table according to the input text read from the file,
in the form: The Frequency's MUST be listed, in order, from largest (at the top) to smallest (at
the bottom). Only the BELOW Tablet Format will be accepted: Letter Comma Space Percentage
Example: A, 2.5% Then, using the Huffman algorithm, construct the optimal prefix binary code
for the table. Design your program to read the input from the input file "infile.dat" Your
program must produce the output, in the file "outfile.dat". consisting of the frequency table for
the source text. the Huffman code for each letter and digit in the source code, and the length of
the coded message in terms of number of bits. MUST use exact file names provided
Solution
#include "FileLoader.h"
#include "CharFreqInVector.h"
#include "LeafNode.h"
#include "TreeFromListConstruction.h"
#include "GenerateHuffFile.h"
#include "Decompressor.h"
#include
#include
#include
int main()
{
{
vector vFile;
vector cvFile;
vector charByte;
vector frequency;
FileLoader File("shakespeare.txt");
vFile = File.loadFileIntoVector();
CharFreqInVector Frequency(vFile);
Frequency.calculateFrequency();
charByte = Frequency.getEachChar();//Frequency.getEachChar(); // need copies of the char
and its frequency to put to a LeafNode
frequency = Frequency.getEachFrequency();//Frequency.getEachFrequency();
TreeFromListConstruction tree(charByte, frequency);
//passing into a class that can modify the list into a binary tree
tree.formTree(); //modify the list into a binary tree
GenerateHuffFile Huff(tree.getTree(), vFile, "compressed.txt",charByte, frequency);
Huff.writeHuffFile();
///////////////////////////////////////////////////////////////////////////////////////decompression time
FileLoader cFile("compressed.txt");
cvFile = cFile.loadFileIntoVector();
CharFreqInVector Formated(cvFile);
Formated.calcFreqInCompressed();
charByte = Formated.getEachChar();//Frequency.getEachChar(); // need copies of the char and
its frequency to put to a LeafNode
frequency = Formated.getEachFrequency();//Frequency.getEachFrequency();
TreeFromListConstruction recontructedTree(charByte, frequency);
recontructedTree.formTree();
Decompressor uncompress(recontructedTree.getTree(), cvFile, "compressed.txt",
"decompressed.txt", vFile.size());
uncompress.remakeFile();
}
cout << _CrtDumpMemoryLeaks(); //no memory leaks yay!
system("pause");
return 0;
}
CharFreqInVector.h
#ifndef CHARFREQINVECTOR_H
#define CHARFREQINVECTOR_H
#include
#include
#include
using namespace std;
class CharFreqInVector
{
public:
CharFreqInVector(vector& charVec);
~CharFreqInVector();
void clearVectors();
void calculateFrequency();
void calcFreqInCompressed();
void displayFrequency();
int convertStringToInt(string aString);
vector getEachChar(){return eachChar;}
vector getEachFrequency(){return eachFrequency;}
private:
vector charVector;
vector eachChar;
vector eachFrequency;
static const int streamSize = 255;
};
#endif
/CharFreqInVector.cpp
#include "CharFreqInVector.h"
CharFreqInVector::CharFreqInVector(vector& charVec)
{
charVector = charVec;
}
void CharFreqInVector::displayFrequency()
{
for(unsigned int i = 0; i < eachChar.size(); i++)
{
cout <<"char:" << eachChar[i] << " freq:" << eachFrequency[i] << endl;
}
}
void CharFreqInVector::calcFreqInCompressed()
{
string intString;
int j = 0;
int i = 0;
while(1)
{
eachChar.push_back(' ');
eachFrequency.push_back(0);
eachChar[j] = charVector[i];
i++;
while(charVector[i] != ',')
{
intString.push_back(charVector[i]);
i++;
}
i++;
eachFrequency[j] = convertStringToInt(intString);
intString.clear();
if(eachChar[j] == '0' || eachFrequency[j] == 0)
{
eachChar.pop_back();
eachFrequency.pop_back();
break;
}
j++;
}
}
int CharFreqInVector::convertStringToInt(string aString)
{
int anInt;
stringstream myStream;
myStream.str(aString);
myStream >> anInt;
return anInt;
}
void CharFreqInVector::calculateFrequency()
{
bool isAlreadyIn = false;
unsigned int i = 0;
unsigned int j = 0;
for(i = 0; i < charVector.size(); i++)
{
for(j = 0; j < eachChar.size(); j++)
{
if(charVector[i] == eachChar[j])
{
eachFrequency[j]++;
isAlreadyIn = true;
break;
}
}
if(!isAlreadyIn)
{
eachChar.push_back(charVector[i]);
eachFrequency.push_back(1);
}
else
isAlreadyIn = false;
}
}
void CharFreqInVector::clearVectors()
{
charVector.clear();
eachChar.clear();
eachFrequency.clear();
}
CharFreqInVector::~CharFreqInVector()
{
clearVectors();
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
//Decompressor.h
#ifndef DECOMPRESSOR_H
#define DECOMPRESSOR_H
#include "LeafNode.h"
class Decompressor
{
public:
Decompressor(vector *aList, vector vFile, string inFile, string outFile, unsigned int origFile);
void remakeFile();
void uncompressChars(unsigned int i);
private:
vector vectorFile;
unsigned int originalFileSize;
string outputFileName;
string inputFileName;
vector *myList;
ofstream fout;
ifstream infile;
};
#endif
//FileLoader.h
#include
#include
#include
#include
using namespace std;
#ifndef FileLoader_H
#define FileLoader_H
class FileLoader
{
public:
FileLoader(string fName);
~FileLoader(){;}
vector loadFileIntoVector();
vector fileVector;
private:
string fileName;
};
#endif
#include "FileLoader.h"
FileLoader::FileLoader(string fName)
{
fileName = fName;
}
vector FileLoader::loadFileIntoVector()
{
ifstream fin;
fin.open(fileName.c_str(), ios::binary);
if(!fin)
{
cout << "unable to open file ";
exit(1);
}
char ch;
while(fin.get(ch))
fileVector.push_back(ch);
fin.close();
return fileVector;
}
//GenerateHuffFile.h
#ifndef GENERATEHUFFFILE_H
#define GENERATEHUFFFILE_H
#include "LeafNode.h"
#include "string"
class GenerateHuffFile
{
public:
GenerateHuffFile(vector *aList, vector vFile, string outPutFile,vector charBytes, vector
frequencies);
void writeHuffFile();//writes the true and bits to file
void writeTreePortionToFile();//writes the tree into a file
void writeBitPortionToFile();//writes the bits to a file
void writeBits(vector bitVector,int i);
void convertBoolVecToBits();//turns the boolean vector representing bits to real bits to write
to file
string getBitsInChar(char dummyByte);
private:
vector *myList;
vector vectorFile;
vector charBytes ;
vector frequencies ;
string outputFile;
ofstream fout;
char dummyByte;
int bitCounter;
int bitPosition;
int totalBitsInFile;
static const int bitsInAByte = 8;
};
#endif
//GenerateHuffFile.cpp
#include "GenerateHuffFile.h"
GenerateHuffFile::GenerateHuffFile(vector *aList, vector vFile, string outFile, vector cBytes,
vector freqs)
{
vectorFile = vFile;
outputFile = outFile;
myList = aList;
bitCounter = 0;
bitPosition = 128;
totalBitsInFile = 0;
charBytes = cBytes;
frequencies = freqs;
}
void GenerateHuffFile::writeHuffFile()
{
fout.open(outputFile.c_str(), ios::binary);
//diplay tree in file
for(unsigned int i = 0; i < charBytes.size(); i++)
{
fout << charBytes[i];
fout << frequencies[i];
fout << ',';
}
fout << "00" << ','; //marker to mark the end of the tree in the file
writeBitPortionToFile();
fout.close();
}
void GenerateHuffFile::writeBits(vector bitVector,int index)
{
// for(unsigned int i = 1; i < bitVector.size();i++)
//{
//cout << bitVector[i];
// }
//cout << endl;
for(unsigned int i = 1; i < bitVector.size(); i++)
{
if(bitVector[i])
{
for(int j = 0; j < bitCounter; j++)
{
bitPosition = bitPosition/2;
}
dummyByte = dummyByte | bitPosition;
bitPosition = 128;
bitCounter++;
totalBitsInFile++;
}
else
{
bitCounter++;
totalBitsInFile++;
}
if(bitCounter == 8 || (index == vectorFile.size() - 1) && (i == bitVector.size() - 1))
{
fout << dummyByte;//cout dummy byte to a file
///cout << getBitsInChar(dummyByte);
bitCounter = 0;
dummyByte = dummyByte & 0;
}
}
}
string GenerateHuffFile::getBitsInChar(char dummyByte)
{
int bitPosition = 128;
string bits;
for(int i = 0; i < 8; i++)
{
for(int j = 0; j < i; j++)
{
bitPosition = bitPosition/2;
}
if((dummyByte & bitPosition) == bitPosition)
{
bits.push_back('1');
}
else
bits.push_back('0');
bitPosition = 128;
}
bits.push_back(' ');
return bits;
}
void GenerateHuffFile::writeBitPortionToFile()
{
bool inChild = false;
Node *aNode;
dummyByte = dummyByte & 0; //clear bit inside to zero
for(unsigned int i = 0; i < vectorFile.size(); i++)
{
for(unsigned int j = 0; j < myList->size(); j++)
{
if(myList[0][j]->getMyChildrenSize() > 0)
{
aNode = myList[0][j]->searchCharByte(vectorFile[i]) ;
writeBits(aNode->getBitVector(),i);
}
}
}
//cout << endl << totalBitsInFile << endl;
}

More Related Content

Similar to Write a program that takes any input text and produces both a frequen.pdf

Similar to Write a program that takes any input text and produces both a frequen.pdf (20)

Tut1
Tut1Tut1
Tut1
 
So basically I worked really hard on this code in my CS150 class and.pdf
So basically I worked really hard on this code in my CS150 class and.pdfSo basically I worked really hard on this code in my CS150 class and.pdf
So basically I worked really hard on this code in my CS150 class and.pdf
 
CInputOutput.ppt
CInputOutput.pptCInputOutput.ppt
CInputOutput.ppt
 
srgoc
srgocsrgoc
srgoc
 
source code which create file and write into it
source code which create file and write into itsource code which create file and write into it
source code which create file and write into it
 
C programming session 08
C programming session 08C programming session 08
C programming session 08
 
String Manipulation Function and Header File Functions
String Manipulation Function and Header File FunctionsString Manipulation Function and Header File Functions
String Manipulation Function and Header File Functions
 
Files
FilesFiles
Files
 
C Language Unit-5
C Language Unit-5C Language Unit-5
C Language Unit-5
 
5java Io
5java Io5java Io
5java Io
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
 
Fundamental of C Programming Language and Basic Input/Output Function
  Fundamental of C Programming Language and Basic Input/Output Function  Fundamental of C Programming Language and Basic Input/Output Function
Fundamental of C Programming Language and Basic Input/Output Function
 
Unit5 (2)
Unit5 (2)Unit5 (2)
Unit5 (2)
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
 
General Functions
General FunctionsGeneral Functions
General Functions
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
C tutorial
C tutorialC tutorial
C tutorial
 
Esoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programmingEsoft Metro Campus - Certificate in c / c++ programming
Esoft Metro Campus - Certificate in c / c++ programming
 
Rust LDN 24 7 19 Oxidising the Command Line
Rust LDN 24 7 19 Oxidising the Command LineRust LDN 24 7 19 Oxidising the Command Line
Rust LDN 24 7 19 Oxidising the Command Line
 

More from arenamobiles123

Consider the following experiment. There are 5 members of a team Jo.pdf
Consider the following experiment. There are 5 members of a team Jo.pdfConsider the following experiment. There are 5 members of a team Jo.pdf
Consider the following experiment. There are 5 members of a team Jo.pdfarenamobiles123
 
A prolific couple had ten children.Through hard work and diligence a.pdf
A prolific couple had ten children.Through hard work and diligence a.pdfA prolific couple had ten children.Through hard work and diligence a.pdf
A prolific couple had ten children.Through hard work and diligence a.pdfarenamobiles123
 
Describe how to use sanction such that a process can send a payload w.pdf
Describe how to use sanction such that a process can send a payload w.pdfDescribe how to use sanction such that a process can send a payload w.pdf
Describe how to use sanction such that a process can send a payload w.pdfarenamobiles123
 
based on this evidence Syconoid sponges were derived from leuconoid.pdf
based on this evidence  Syconoid sponges were derived from leuconoid.pdfbased on this evidence  Syconoid sponges were derived from leuconoid.pdf
based on this evidence Syconoid sponges were derived from leuconoid.pdfarenamobiles123
 
At noon Joyce drove to the lake at 30 miles per hour, but she made t.pdf
At noon Joyce drove to the lake at 30 miles per hour, but she made t.pdfAt noon Joyce drove to the lake at 30 miles per hour, but she made t.pdf
At noon Joyce drove to the lake at 30 miles per hour, but she made t.pdfarenamobiles123
 
A) If a DNA double helix that is 100 base pairs in length has 32 a.pdf
A) If a DNA double helix that is 100 base pairs in length has 32 a.pdfA) If a DNA double helix that is 100 base pairs in length has 32 a.pdf
A) If a DNA double helix that is 100 base pairs in length has 32 a.pdfarenamobiles123
 
Chapter2...22.            (Problem 3) Which of the following are.pdf
Chapter2...22.            (Problem 3) Which of the following are.pdfChapter2...22.            (Problem 3) Which of the following are.pdf
Chapter2...22.            (Problem 3) Which of the following are.pdfarenamobiles123
 
why is reversibility an important characteristic of childrens .pdf
why is reversibility an important characteristic of childrens .pdfwhy is reversibility an important characteristic of childrens .pdf
why is reversibility an important characteristic of childrens .pdfarenamobiles123
 
Which of the following tools is used to generate the profiles and se.pdf
Which of the following tools is used to generate the profiles and se.pdfWhich of the following tools is used to generate the profiles and se.pdf
Which of the following tools is used to generate the profiles and se.pdfarenamobiles123
 
What are 2 ways that Alexander Hamilton’s ideas influenced the Unite.pdf
What are 2 ways that Alexander Hamilton’s ideas influenced the Unite.pdfWhat are 2 ways that Alexander Hamilton’s ideas influenced the Unite.pdf
What are 2 ways that Alexander Hamilton’s ideas influenced the Unite.pdfarenamobiles123
 
Which of the following is a non-respiratory function of the lunga.pdf
Which of the following is a non-respiratory function of the lunga.pdfWhich of the following is a non-respiratory function of the lunga.pdf
Which of the following is a non-respiratory function of the lunga.pdfarenamobiles123
 
Which key numbers help you asses your performance in an organizat.pdf
Which key numbers help you asses your performance in an organizat.pdfWhich key numbers help you asses your performance in an organizat.pdf
Which key numbers help you asses your performance in an organizat.pdfarenamobiles123
 
what two things can system elements do with energy in the system.pdf
what two things can system elements do with energy in the system.pdfwhat two things can system elements do with energy in the system.pdf
what two things can system elements do with energy in the system.pdfarenamobiles123
 
What is an Intervening Variable, Casual Prior Variable, and Partial .pdf
What is an Intervening Variable, Casual Prior Variable, and Partial .pdfWhat is an Intervening Variable, Casual Prior Variable, and Partial .pdf
What is an Intervening Variable, Casual Prior Variable, and Partial .pdfarenamobiles123
 
The basic functional plan of the gonads includes all of the followin.pdf
The basic functional plan of the gonads includes all of the followin.pdfThe basic functional plan of the gonads includes all of the followin.pdf
The basic functional plan of the gonads includes all of the followin.pdfarenamobiles123
 
The color of the small lymphocytes cytoplasm is a very () lilac a.pdf
The color of the small lymphocytes cytoplasm is a very () lilac a.pdfThe color of the small lymphocytes cytoplasm is a very () lilac a.pdf
The color of the small lymphocytes cytoplasm is a very () lilac a.pdfarenamobiles123
 
Social behavior in termites does not include the reproductive isolat.pdf
Social behavior in termites does not include the reproductive isolat.pdfSocial behavior in termites does not include the reproductive isolat.pdf
Social behavior in termites does not include the reproductive isolat.pdfarenamobiles123
 
Sam, a 27-year-old African-American male, was admitted to the hospit.pdf
Sam, a 27-year-old African-American male, was admitted to the hospit.pdfSam, a 27-year-old African-American male, was admitted to the hospit.pdf
Sam, a 27-year-old African-American male, was admitted to the hospit.pdfarenamobiles123
 
question 4) Which of following elements are nonmetals Na O Ar S .pdf
question 4) Which of following elements are nonmetals Na O Ar S .pdfquestion 4) Which of following elements are nonmetals Na O Ar S .pdf
question 4) Which of following elements are nonmetals Na O Ar S .pdfarenamobiles123
 
8.15 Program Playlist (C++) You will be building a linked list. Mak.pdf
8.15 Program Playlist (C++) You will be building a linked list. Mak.pdf8.15 Program Playlist (C++) You will be building a linked list. Mak.pdf
8.15 Program Playlist (C++) You will be building a linked list. Mak.pdfarenamobiles123
 

More from arenamobiles123 (20)

Consider the following experiment. There are 5 members of a team Jo.pdf
Consider the following experiment. There are 5 members of a team Jo.pdfConsider the following experiment. There are 5 members of a team Jo.pdf
Consider the following experiment. There are 5 members of a team Jo.pdf
 
A prolific couple had ten children.Through hard work and diligence a.pdf
A prolific couple had ten children.Through hard work and diligence a.pdfA prolific couple had ten children.Through hard work and diligence a.pdf
A prolific couple had ten children.Through hard work and diligence a.pdf
 
Describe how to use sanction such that a process can send a payload w.pdf
Describe how to use sanction such that a process can send a payload w.pdfDescribe how to use sanction such that a process can send a payload w.pdf
Describe how to use sanction such that a process can send a payload w.pdf
 
based on this evidence Syconoid sponges were derived from leuconoid.pdf
based on this evidence  Syconoid sponges were derived from leuconoid.pdfbased on this evidence  Syconoid sponges were derived from leuconoid.pdf
based on this evidence Syconoid sponges were derived from leuconoid.pdf
 
At noon Joyce drove to the lake at 30 miles per hour, but she made t.pdf
At noon Joyce drove to the lake at 30 miles per hour, but she made t.pdfAt noon Joyce drove to the lake at 30 miles per hour, but she made t.pdf
At noon Joyce drove to the lake at 30 miles per hour, but she made t.pdf
 
A) If a DNA double helix that is 100 base pairs in length has 32 a.pdf
A) If a DNA double helix that is 100 base pairs in length has 32 a.pdfA) If a DNA double helix that is 100 base pairs in length has 32 a.pdf
A) If a DNA double helix that is 100 base pairs in length has 32 a.pdf
 
Chapter2...22.            (Problem 3) Which of the following are.pdf
Chapter2...22.            (Problem 3) Which of the following are.pdfChapter2...22.            (Problem 3) Which of the following are.pdf
Chapter2...22.            (Problem 3) Which of the following are.pdf
 
why is reversibility an important characteristic of childrens .pdf
why is reversibility an important characteristic of childrens .pdfwhy is reversibility an important characteristic of childrens .pdf
why is reversibility an important characteristic of childrens .pdf
 
Which of the following tools is used to generate the profiles and se.pdf
Which of the following tools is used to generate the profiles and se.pdfWhich of the following tools is used to generate the profiles and se.pdf
Which of the following tools is used to generate the profiles and se.pdf
 
What are 2 ways that Alexander Hamilton’s ideas influenced the Unite.pdf
What are 2 ways that Alexander Hamilton’s ideas influenced the Unite.pdfWhat are 2 ways that Alexander Hamilton’s ideas influenced the Unite.pdf
What are 2 ways that Alexander Hamilton’s ideas influenced the Unite.pdf
 
Which of the following is a non-respiratory function of the lunga.pdf
Which of the following is a non-respiratory function of the lunga.pdfWhich of the following is a non-respiratory function of the lunga.pdf
Which of the following is a non-respiratory function of the lunga.pdf
 
Which key numbers help you asses your performance in an organizat.pdf
Which key numbers help you asses your performance in an organizat.pdfWhich key numbers help you asses your performance in an organizat.pdf
Which key numbers help you asses your performance in an organizat.pdf
 
what two things can system elements do with energy in the system.pdf
what two things can system elements do with energy in the system.pdfwhat two things can system elements do with energy in the system.pdf
what two things can system elements do with energy in the system.pdf
 
What is an Intervening Variable, Casual Prior Variable, and Partial .pdf
What is an Intervening Variable, Casual Prior Variable, and Partial .pdfWhat is an Intervening Variable, Casual Prior Variable, and Partial .pdf
What is an Intervening Variable, Casual Prior Variable, and Partial .pdf
 
The basic functional plan of the gonads includes all of the followin.pdf
The basic functional plan of the gonads includes all of the followin.pdfThe basic functional plan of the gonads includes all of the followin.pdf
The basic functional plan of the gonads includes all of the followin.pdf
 
The color of the small lymphocytes cytoplasm is a very () lilac a.pdf
The color of the small lymphocytes cytoplasm is a very () lilac a.pdfThe color of the small lymphocytes cytoplasm is a very () lilac a.pdf
The color of the small lymphocytes cytoplasm is a very () lilac a.pdf
 
Social behavior in termites does not include the reproductive isolat.pdf
Social behavior in termites does not include the reproductive isolat.pdfSocial behavior in termites does not include the reproductive isolat.pdf
Social behavior in termites does not include the reproductive isolat.pdf
 
Sam, a 27-year-old African-American male, was admitted to the hospit.pdf
Sam, a 27-year-old African-American male, was admitted to the hospit.pdfSam, a 27-year-old African-American male, was admitted to the hospit.pdf
Sam, a 27-year-old African-American male, was admitted to the hospit.pdf
 
question 4) Which of following elements are nonmetals Na O Ar S .pdf
question 4) Which of following elements are nonmetals Na O Ar S .pdfquestion 4) Which of following elements are nonmetals Na O Ar S .pdf
question 4) Which of following elements are nonmetals Na O Ar S .pdf
 
8.15 Program Playlist (C++) You will be building a linked list. Mak.pdf
8.15 Program Playlist (C++) You will be building a linked list. Mak.pdf8.15 Program Playlist (C++) You will be building a linked list. Mak.pdf
8.15 Program Playlist (C++) You will be building a linked list. Mak.pdf
 

Recently uploaded

How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17Celine George
 
Introduction to TechSoup’s Digital Marketing Services and Use Cases
Introduction to TechSoup’s Digital Marketing  Services and Use CasesIntroduction to TechSoup’s Digital Marketing  Services and Use Cases
Introduction to TechSoup’s Digital Marketing Services and Use CasesTechSoup
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17Celine George
 
How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17Celine George
 
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
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfDr Vijay Vishwakarma
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningMarc Dusseiller Dusjagr
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...EduSkills OECD
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxannathomasp01
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsNbelano25
 
Ernest Hemingway's For Whom the Bell Tolls
Ernest Hemingway's For Whom the Bell TollsErnest Hemingway's For Whom the Bell Tolls
Ernest Hemingway's For Whom the Bell TollsPallavi Parmar
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxDr. Ravikiran H M Gowda
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024Elizabeth Walsh
 
PANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxPANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxakanksha16arora
 
Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxAdelaideRefugio
 
Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Celine George
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxJisc
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jisc
 

Recently uploaded (20)

How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17How to Add New Custom Addons Path in Odoo 17
How to Add New Custom Addons Path in Odoo 17
 
Introduction to TechSoup’s Digital Marketing Services and Use Cases
Introduction to TechSoup’s Digital Marketing  Services and Use CasesIntroduction to TechSoup’s Digital Marketing  Services and Use Cases
Introduction to TechSoup’s Digital Marketing Services and Use Cases
 
OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...OS-operating systems- ch05 (CPU Scheduling) ...
OS-operating systems- ch05 (CPU Scheduling) ...
 
How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17How to Manage Call for Tendor in Odoo 17
How to Manage Call for Tendor in Odoo 17
 
How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17How to Add a Tool Tip to a Field in Odoo 17
How to Add a Tool Tip to a Field in Odoo 17
 
diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....diagnosting testing bsc 2nd sem.pptx....
diagnosting testing bsc 2nd sem.pptx....
 
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdfUnit 3 Emotional Intelligence and Spiritual Intelligence.pdf
Unit 3 Emotional Intelligence and Spiritual Intelligence.pdf
 
dusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learningdusjagr & nano talk on open tools for agriculture research and learning
dusjagr & nano talk on open tools for agriculture research and learning
 
Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...Andreas Schleicher presents at the launch of What does child empowerment mean...
Andreas Schleicher presents at the launch of What does child empowerment mean...
 
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptxCOMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
COMMUNICATING NEGATIVE NEWS - APPROACHES .pptx
 
Tatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf artsTatlong Kwento ni Lola basyang-1.pdf arts
Tatlong Kwento ni Lola basyang-1.pdf arts
 
Ernest Hemingway's For Whom the Bell Tolls
Ernest Hemingway's For Whom the Bell TollsErnest Hemingway's For Whom the Bell Tolls
Ernest Hemingway's For Whom the Bell Tolls
 
REMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptxREMIFENTANIL: An Ultra short acting opioid.pptx
REMIFENTANIL: An Ultra short acting opioid.pptx
 
FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024FSB Advising Checklist - Orientation 2024
FSB Advising Checklist - Orientation 2024
 
PANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptxPANDITA RAMABAI- Indian political thought GENDER.pptx
PANDITA RAMABAI- Indian political thought GENDER.pptx
 
Observing-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptxObserving-Correct-Grammar-in-Making-Definitions.pptx
Observing-Correct-Grammar-in-Making-Definitions.pptx
 
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
 
Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17Model Attribute _rec_name in the Odoo 17
Model Attribute _rec_name in the Odoo 17
 
Wellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptxWellbeing inclusion and digital dystopias.pptx
Wellbeing inclusion and digital dystopias.pptx
 
Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)Jamworks pilot and AI at Jisc (20/03/2024)
Jamworks pilot and AI at Jisc (20/03/2024)
 

Write a program that takes any input text and produces both a frequen.pdf

  • 1. Write a program that takes any input text and produces both a frequency table and the corresponding Huffman code. Take approximately 360 words from any English document as your input text. Ignore all blanks, all punctuation marks, al special symbols. Create an input file with this input text. Construct the frequency table according to the input text read from the file, in the form: The Frequency's MUST be listed, in order, from largest (at the top) to smallest (at the bottom). Only the BELOW Tablet Format will be accepted: Letter Comma Space Percentage Example: A, 2.5% Then, using the Huffman algorithm, construct the optimal prefix binary code for the table. Design your program to read the input from the input file "infile.dat" Your program must produce the output, in the file "outfile.dat". consisting of the frequency table for the source text. the Huffman code for each letter and digit in the source code, and the length of the coded message in terms of number of bits. MUST use exact file names provided Solution #include "FileLoader.h" #include "CharFreqInVector.h" #include "LeafNode.h" #include "TreeFromListConstruction.h" #include "GenerateHuffFile.h" #include "Decompressor.h" #include #include #include int main() { { vector vFile; vector cvFile; vector charByte; vector frequency; FileLoader File("shakespeare.txt"); vFile = File.loadFileIntoVector(); CharFreqInVector Frequency(vFile);
  • 2. Frequency.calculateFrequency(); charByte = Frequency.getEachChar();//Frequency.getEachChar(); // need copies of the char and its frequency to put to a LeafNode frequency = Frequency.getEachFrequency();//Frequency.getEachFrequency(); TreeFromListConstruction tree(charByte, frequency); //passing into a class that can modify the list into a binary tree tree.formTree(); //modify the list into a binary tree GenerateHuffFile Huff(tree.getTree(), vFile, "compressed.txt",charByte, frequency); Huff.writeHuffFile(); ///////////////////////////////////////////////////////////////////////////////////////decompression time FileLoader cFile("compressed.txt"); cvFile = cFile.loadFileIntoVector(); CharFreqInVector Formated(cvFile); Formated.calcFreqInCompressed(); charByte = Formated.getEachChar();//Frequency.getEachChar(); // need copies of the char and its frequency to put to a LeafNode frequency = Formated.getEachFrequency();//Frequency.getEachFrequency(); TreeFromListConstruction recontructedTree(charByte, frequency); recontructedTree.formTree(); Decompressor uncompress(recontructedTree.getTree(), cvFile, "compressed.txt", "decompressed.txt", vFile.size()); uncompress.remakeFile(); } cout << _CrtDumpMemoryLeaks(); //no memory leaks yay! system("pause"); return 0; } CharFreqInVector.h #ifndef CHARFREQINVECTOR_H #define CHARFREQINVECTOR_H #include
  • 3. #include #include using namespace std; class CharFreqInVector { public: CharFreqInVector(vector& charVec); ~CharFreqInVector(); void clearVectors(); void calculateFrequency(); void calcFreqInCompressed(); void displayFrequency(); int convertStringToInt(string aString); vector getEachChar(){return eachChar;} vector getEachFrequency(){return eachFrequency;} private: vector charVector; vector eachChar; vector eachFrequency; static const int streamSize = 255; }; #endif /CharFreqInVector.cpp #include "CharFreqInVector.h" CharFreqInVector::CharFreqInVector(vector& charVec) { charVector = charVec; } void CharFreqInVector::displayFrequency() { for(unsigned int i = 0; i < eachChar.size(); i++) { cout <<"char:" << eachChar[i] << " freq:" << eachFrequency[i] << endl;
  • 4. } } void CharFreqInVector::calcFreqInCompressed() { string intString; int j = 0; int i = 0; while(1) { eachChar.push_back(' '); eachFrequency.push_back(0); eachChar[j] = charVector[i]; i++; while(charVector[i] != ',') { intString.push_back(charVector[i]); i++; } i++; eachFrequency[j] = convertStringToInt(intString); intString.clear(); if(eachChar[j] == '0' || eachFrequency[j] == 0) { eachChar.pop_back(); eachFrequency.pop_back(); break; } j++; } } int CharFreqInVector::convertStringToInt(string aString) { int anInt;
  • 5. stringstream myStream; myStream.str(aString); myStream >> anInt; return anInt; } void CharFreqInVector::calculateFrequency() { bool isAlreadyIn = false; unsigned int i = 0; unsigned int j = 0; for(i = 0; i < charVector.size(); i++) { for(j = 0; j < eachChar.size(); j++) { if(charVector[i] == eachChar[j]) { eachFrequency[j]++; isAlreadyIn = true; break; } } if(!isAlreadyIn) { eachChar.push_back(charVector[i]); eachFrequency.push_back(1); } else isAlreadyIn = false; } } void CharFreqInVector::clearVectors() { charVector.clear(); eachChar.clear(); eachFrequency.clear();
  • 7. public: Decompressor(vector *aList, vector vFile, string inFile, string outFile, unsigned int origFile); void remakeFile(); void uncompressChars(unsigned int i); private: vector vectorFile; unsigned int originalFileSize; string outputFileName; string inputFileName; vector *myList; ofstream fout; ifstream infile; }; #endif //FileLoader.h #include #include #include #include using namespace std; #ifndef FileLoader_H #define FileLoader_H class FileLoader { public: FileLoader(string fName); ~FileLoader(){;} vector loadFileIntoVector(); vector fileVector; private: string fileName; }; #endif
  • 8. #include "FileLoader.h" FileLoader::FileLoader(string fName) { fileName = fName; } vector FileLoader::loadFileIntoVector() { ifstream fin; fin.open(fileName.c_str(), ios::binary); if(!fin) { cout << "unable to open file "; exit(1); } char ch; while(fin.get(ch)) fileVector.push_back(ch); fin.close(); return fileVector; } //GenerateHuffFile.h #ifndef GENERATEHUFFFILE_H #define GENERATEHUFFFILE_H #include "LeafNode.h" #include "string" class GenerateHuffFile { public:
  • 9. GenerateHuffFile(vector *aList, vector vFile, string outPutFile,vector charBytes, vector frequencies); void writeHuffFile();//writes the true and bits to file void writeTreePortionToFile();//writes the tree into a file void writeBitPortionToFile();//writes the bits to a file void writeBits(vector bitVector,int i); void convertBoolVecToBits();//turns the boolean vector representing bits to real bits to write to file string getBitsInChar(char dummyByte); private: vector *myList; vector vectorFile; vector charBytes ; vector frequencies ; string outputFile; ofstream fout; char dummyByte; int bitCounter; int bitPosition; int totalBitsInFile; static const int bitsInAByte = 8; }; #endif //GenerateHuffFile.cpp #include "GenerateHuffFile.h" GenerateHuffFile::GenerateHuffFile(vector *aList, vector vFile, string outFile, vector cBytes, vector freqs) { vectorFile = vFile; outputFile = outFile; myList = aList; bitCounter = 0; bitPosition = 128;
  • 10. totalBitsInFile = 0; charBytes = cBytes; frequencies = freqs; } void GenerateHuffFile::writeHuffFile() { fout.open(outputFile.c_str(), ios::binary); //diplay tree in file for(unsigned int i = 0; i < charBytes.size(); i++) { fout << charBytes[i]; fout << frequencies[i]; fout << ','; } fout << "00" << ','; //marker to mark the end of the tree in the file writeBitPortionToFile(); fout.close(); } void GenerateHuffFile::writeBits(vector bitVector,int index) { // for(unsigned int i = 1; i < bitVector.size();i++) //{ //cout << bitVector[i]; // } //cout << endl; for(unsigned int i = 1; i < bitVector.size(); i++) { if(bitVector[i])
  • 11. { for(int j = 0; j < bitCounter; j++) { bitPosition = bitPosition/2; } dummyByte = dummyByte | bitPosition; bitPosition = 128; bitCounter++; totalBitsInFile++; } else { bitCounter++; totalBitsInFile++; } if(bitCounter == 8 || (index == vectorFile.size() - 1) && (i == bitVector.size() - 1)) { fout << dummyByte;//cout dummy byte to a file ///cout << getBitsInChar(dummyByte); bitCounter = 0; dummyByte = dummyByte & 0; } } } string GenerateHuffFile::getBitsInChar(char dummyByte) { int bitPosition = 128; string bits; for(int i = 0; i < 8; i++) { for(int j = 0; j < i; j++) {
  • 12. bitPosition = bitPosition/2; } if((dummyByte & bitPosition) == bitPosition) { bits.push_back('1'); } else bits.push_back('0'); bitPosition = 128; } bits.push_back(' '); return bits; } void GenerateHuffFile::writeBitPortionToFile() { bool inChild = false; Node *aNode; dummyByte = dummyByte & 0; //clear bit inside to zero for(unsigned int i = 0; i < vectorFile.size(); i++) { for(unsigned int j = 0; j < myList->size(); j++) { if(myList[0][j]->getMyChildrenSize() > 0) { aNode = myList[0][j]->searchCharByte(vectorFile[i]) ; writeBits(aNode->getBitVector(),i); } } } //cout << endl << totalBitsInFile << endl;
  • 13. }