Anda di halaman 1dari 4

PROBLEM STATEMENT

Create a half page document (unformatted text) using notepad. Write a C/C++ code to implement dynamic
Huffman encoding and decoding algorithms to compress this text. Assuming 8 bit/character, calculate the
average no. of bits/character in the coded bitstream and compression ratio achieved. What are the
limitations of dynamic Huffman coding algorithm?

C++ Program Code for Huffman Coding:

#include <iostream>
#include <string>
#include <queue>
#include <unordered_map>
using namespace std;
int total = 0;

// A Tree node
struct Node
{
char ch;
int freq;
Node *left, *right;
};

// Function to allocate a new tree node


Node* getNode(char ch, int freq, Node* left, Node* right)
{
Node* node = new Node();

node->ch = ch;
node->freq = freq;
node->left = left;
node->right = right;

return node;
}

struct comp
{
bool operator()(Node* l, Node* r)
{
// highest priority item has lowest frequency
return l->freq > r->freq;
}
};

void encode(Node* root, string str,


unordered_map<char, string> &huffmanCode)
{
if (root == nullptr)
return;

// found a leaf node


if (!root->left && !root->right) {
huffmanCode[root->ch] = str;
}

encode(root->left, str + "0", huffmanCode);


encode(root->right, str + "1", huffmanCode);
}

// traverse the Huffman Tree and decode the encoded string


void decode(Node* root, int &index, string str)
{
if (root == nullptr) {
return;
}

// found a leaf node


if (!root->left && !root->right)
{
cout << root->ch;
return;
}

index++;

if (str[index] =='0')
decode(root->left, index, str);
else
decode(root->right, index, str);
}

// Builds Huffman Tree and decode given input text


void buildHuffmanTree(string text)
{
// count frequency of appearance of each character
// and store it in a map
unordered_map<char, int> freq;

for (char ch: text) {


freq[ch]++;
}

// for (auto pair: freq) {


// cout << pair.first<<" "<<pair.second<<endl;
// }

priority_queue<Node*, vector<Node*>, comp> pq;

// Create a leaf node for each character and add it


// to the priority queue.
for (auto pair: freq) {
pq.push(getNode(pair.first, pair.second, nullptr, nullptr));
}

// do till there is more than one node in the queue


while (pq.size() != 1)
{
// Remove the two nodes of highest priority
// (lowest frequency) from the queue
Node *left = pq.top(); pq.pop();
Node *right = pq.top(); pq.pop();

int sum = left->freq + right->freq;


pq.push(getNode('\0', sum, left, right));
}

Node* root = pq.top();

unordered_map<char, string> huffmanCode;


encode(root, "", huffmanCode);

cout << "Huffman Codes are :\n" << '\n';


for (auto pair: huffmanCode) {
cout << pair.first << " " << pair.second <<" "<< "Length in bits: " <<pair.second.length()<< '\n';

}
for (auto pair: huffmanCode ) {
total = total+pair.second.length() * freq.at(pair.first);

cout << "\nOriginal string was :\n" << text << '\n';

// print encoded string


string str = "";
for (char ch: text) {
str += huffmanCode[ch];
}

cout << "\nEncoded string is :\n" << str << '\n';

int index = -1;


cout << "\nDecoded string is: \n";
while (index < (int)str.size() - 2) {
decode(root, index, str);
}
}

int main()
{

string text = "An accident is an unpredicted and unintentional event. Considering the alarming increase in the number of motor
bike riders and the number of accidents happening in our country, this system ensures to make the two-wheeler driving safer than before
for the rider. Most injuries resulting from motorcycle crashes are head injuries and wearing a good helmet is the single most effective way
of protecting ourselves. But due to the rider’s negligence in wearing a helmet contributes to accident injuries. Alsothe lack of treatment in
proper time is another major reason for half of the deaths in road accidents. This system aims to encourage and enforce the rider to wear
helmet before driving. With the help of smart helmet, we can ensure that the vehicle will start only when the helmet is worn. Secondly,
the Smart helmet also reduces the possibility of accidents due to drink and drive. This is done with the help of alcohol sensors used which
detects the presence of alcohol and doesn’t let the vehicle to start. Thirdly, In case of accidents, the Smart Helmet is enabled to detect the
fall of vehicle and send the live location of accident to emergency contact numbers such as ambulance, family and friends on time to
provide quick assistance for the injured person. When the rider met with an accident and the helmet hits the ground, the vibration sensor
which is embedded in the helmet senses the vibration frequency and transfers the value to the Arduino Uno module that is interfaced to
it. While vibration threshold frequency exceeds the programmed maximum limit, the Arduino Uno board extracts GPS data from the GPS
module and the message with all the necessary information is sent quickly to the registered emergency contacts of the rider. This system
assures to provide immediate assistance to the victim of the accident. The results give exact locations of the accident. ";
cout<<"\n";

buildHuffmanTree(text);
cout<<"\n";

cout<<"Length of UnCompressed text:"<<text.length()*8<<endl;


cout<<"Length of Compressed text:"<<total<<endl;

double ratio = (float)(text.length()*8)/(float)total;


cout<<"Compression ratio :"<< " " <<ratio<<endl;
return 0;
}

OUTPUT:-
Huffman Codes are :
111 Length in bits: 3
t 1101 Length in bits: 4
j 110011111 Length in bits: 9
W 1100111101 Length in bits: 10
S 110011101 Length in bits: 9
u 110010 Length in bits: 6
d 11000 Length in bits: 5
c 10111 Length in bits: 5
f 101101 Length in bits: 6
y 1011001 Length in bits: 7
M 10110001010 Length in bits: 11
v 1100110 Length in bits: 7
G 1011000100 Length in bits: 10
P 1011000011 Length in bits: 10
- 10110000100 Length in bits: 11
q 101100011 Length in bits: 9
B 10110000011 Length in bits: 11
i 1010 Length in bits: 4
, 10011110 Length in bits: 8
x 100111111 Length in bits: 9
I 10110000010 Length in bits: 11
H 10110000101 Length in bits: 11
w 1001110 Length in bits: 7
b 1001101 Length in bits: 7
A 110011100 Length in bits: 9
p 1001100 Length in bits: 7
U 1100111100 Length in bits: 10
? 1001111101 Length in bits: 10
l 10010 Length in bits: 5
? 1011000000 Length in bits: 10
n 1000 Length in bits: 4
o 0101 Length in bits: 4
a 0010 Length in bits: 4
m 00011 Length in bits: 5
e 011 Length in bits: 3
s 0011 Length in bits: 4
. 0001011 Length in bits: 7
T 00010100 Length in bits: 8
k 00010101 Length in bits: 8
? 1001111100 Length in bits: 10
C 10110001011 Length in bits: 11
r 0100 Length in bits: 4
g 000100 Length in bits: 6
h 0000 Length in bits: 4

Length of UnCompressed text:15080


Length of Compressed text:8030
Compression ratio : 1.87796

DISCUSSIONS ON RESULTS:-
1. We have implemented Dynamic Huffman Coding in C++.
2. The given unformatted string is encoded and decoded as shown and the compression ratio achieved is 1.8952.
3. The limitations of Dynamic Huffman coding are:-
 It is used rarely in practice, since the cost of updating the tree makes it more complicated and thus slower than
optimized adaptive arithmetic coding, which is more flexible and has better compression.
 Adaptive Huffman encodes slightly more than efficiently than Huffman, but it is slower.
 It is more sensitive to transmission errors as the single loss ruins the whole code.

Anda mungkin juga menyukai