SlideShare a Scribd company logo
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

Tut1
Tut1Tut1
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
eyewaregallery
 
srgoc
srgocsrgoc
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
melakusisay507
 
C programming session 08
C programming session 08C programming session 08
C programming session 08Dushmanta Nath
 
String Manipulation Function and Header File Functions
String Manipulation Function and Header File FunctionsString Manipulation Function and Header File Functions
C Language Unit-5
C Language Unit-5C Language Unit-5
C Language Unit-5
kasaragadda srinivasrao
 
Solid C++ by Example
Solid C++ by ExampleSolid C++ by Example
Solid C++ by Example
Olve Maudal
 
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
imtiazalijoono
 
Unit5 (2)
Unit5 (2)Unit5 (2)
Unit5 (2)mrecedu
 
C programming language tutorial
C programming language tutorial C programming language tutorial
C programming language tutorial
javaTpoint s
 
General Functions
General FunctionsGeneral Functions
General Functions
BabuDevanandam
 
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
Rasan Samarasinghe
 
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
Matt Provost
 

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.pdf
arenamobiles123
 
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
arenamobiles123
 
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
arenamobiles123
 
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
arenamobiles123
 
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
arenamobiles123
 
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
arenamobiles123
 
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
arenamobiles123
 
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
arenamobiles123
 
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
arenamobiles123
 
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
arenamobiles123
 
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
arenamobiles123
 
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
arenamobiles123
 
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
arenamobiles123
 
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
arenamobiles123
 
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
arenamobiles123
 
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
arenamobiles123
 
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
arenamobiles123
 
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
arenamobiles123
 
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
arenamobiles123
 
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
arenamobiles123
 

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

The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
Delapenabediema
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
Vikramjit Singh
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
Ashokrao Mane college of Pharmacy Peth-Vadgaon
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
RaedMohamed3
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
Jisc
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
Jean Carlos Nunes Paixão
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
DeeptiGupta154
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
Peter Windle
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
CarlosHernanMontoyab2
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
Pavel ( NSTU)
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
camakaiclarkmusic
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
kaushalkr1407
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
Nguyen Thanh Tu Collection
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
Special education needs
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
heathfieldcps1
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
Celine George
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
Jheel Barad
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
DhatriParmar
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
Anna Sz.
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Po-Chuan Chen
 

Recently uploaded (20)

The Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official PublicationThe Challenger.pdf DNHS Official Publication
The Challenger.pdf DNHS Official Publication
 
Digital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and ResearchDigital Tools and AI for Teaching Learning and Research
Digital Tools and AI for Teaching Learning and Research
 
Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.Biological Screening of Herbal Drugs in detailed.
Biological Screening of Herbal Drugs in detailed.
 
Palestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptxPalestine last event orientationfvgnh .pptx
Palestine last event orientationfvgnh .pptx
 
How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...How libraries can support authors with open access requirements for UKRI fund...
How libraries can support authors with open access requirements for UKRI fund...
 
Lapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdfLapbook sobre os Regimes Totalitários.pdf
Lapbook sobre os Regimes Totalitários.pdf
 
Overview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with MechanismOverview on Edible Vaccine: Pros & Cons with Mechanism
Overview on Edible Vaccine: Pros & Cons with Mechanism
 
Embracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic ImperativeEmbracing GenAI - A Strategic Imperative
Embracing GenAI - A Strategic Imperative
 
678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf678020731-Sumas-y-Restas-Para-Colorear.pdf
678020731-Sumas-y-Restas-Para-Colorear.pdf
 
Synthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptxSynthetic Fiber Construction in lab .pptx
Synthetic Fiber Construction in lab .pptx
 
CACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdfCACJapan - GROUP Presentation 1- Wk 4.pdf
CACJapan - GROUP Presentation 1- Wk 4.pdf
 
The Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdfThe Roman Empire A Historical Colossus.pdf
The Roman Empire A Historical Colossus.pdf
 
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
BÀI TẬP BỔ TRỢ TIẾNG ANH GLOBAL SUCCESS LỚP 3 - CẢ NĂM (CÓ FILE NGHE VÀ ĐÁP Á...
 
special B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdfspecial B.ed 2nd year old paper_20240531.pdf
special B.ed 2nd year old paper_20240531.pdf
 
The basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptxThe basics of sentences session 5pptx.pptx
The basics of sentences session 5pptx.pptx
 
Model Attribute Check Company Auto Property
Model Attribute  Check Company Auto PropertyModel Attribute  Check Company Auto Property
Model Attribute Check Company Auto Property
 
Instructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptxInstructions for Submissions thorugh G- Classroom.pptx
Instructions for Submissions thorugh G- Classroom.pptx
 
The Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptxThe Accursed House by Émile Gaboriau.pptx
The Accursed House by Émile Gaboriau.pptx
 
Polish students' mobility in the Czech Republic
Polish students' mobility in the Czech RepublicPolish students' mobility in the Czech Republic
Polish students' mobility in the Czech Republic
 
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdfAdversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
Adversarial Attention Modeling for Multi-dimensional Emotion Regression.pdf
 

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. }