-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.cpp
More file actions
199 lines (155 loc) · 5.23 KB
/
code.cpp
File metadata and controls
199 lines (155 loc) · 5.23 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
#include <iostream>
#include <string>
#include <queue>
#include <unordered_map>
using namespace std;
// 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;
}
// Comparison object to be used to order the heap
struct comp
{
bool operator()(Node* l, Node* r)
{
// highest priority item has lowest frequency
return l->freq > r->freq;
}
};
// Encoding function to Traverse the Huffman Tree to generate Huffman Codes.
void encode(Node* root, string binStr, unordered_map<char, string> &huffmanCode)
{
if (root == nullptr)
return;
// Found a leaf node (No left child & No right child)
if (!root->left && !root->right) {
// Store the Huffman Code for this character in the map
huffmanCode[root->ch] = binStr;
return;
}
// Traverse left child with '0' appended to the binary string
encode(root->left, binStr + "0", huffmanCode);
// Traverse right child with '1' appended to the binary string
encode(root->right, binStr + "1", huffmanCode);
}
// traverse the Huffman Tree and decode the encoded string
void decode(Node* root, int &index, string str,string &decodedString)
{
if (root == nullptr) {
return;
}
// found a leaf node
if (!root->left && !root->right)
{
cout << root->ch;
decodedString+=root->ch;
return;
}
index++;
if (str[index] =='0')
decode(root->left, index, str,decodedString);
else
decode(root->right, index, str,decodedString);
}
double calculateCompressionFactor(int inputSizeBits, int encodedSizeBits) {
double compressionFactor = 1.0 - ((double)(encodedSizeBits) / inputSizeBits);
return compressionFactor * 100.0; // Convertion to percentage % .
}
int hammingDistance(const string& str1, const string& str2) {
int distance = 0;
int len = min(str1.length(), str2.length());
for (int i = 0; i < len; ++i) {
if (str1[i] != str2[i]) {
++distance;
}
}
// Add the remaining characters in the longer string, if any
distance += abs((int)(str1.length() - str2.length()));
return distance;
}
void HuffmanCompression(string text)
{
// Count frequency of each character and store them in a map
unordered_map<char, int> freq;
for (char ch: text) {
freq[ch]++;
}
// Create a priority queue to store the nodes of Huffman tree;
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));
}
while (pq.size() != 1)
{
// Extract the two lowest frequency nodes as left and right children
Node *left = pq.top(); pq.pop();
Node *right = pq.top(); pq.pop();
// Create an internal node combining the two lowest-frequency nodes
// and enqueue it with a frequency equal to the sum of the children's frequencies.
int sum = left->freq + right->freq;
pq.push(getNode('\0', sum, left, right));
}
//Last node left will be root, root stores pointer to root of Huffman Tree.
Node* root = pq.top();
// Traverse the Huffman Tree to generate Huffman Codes and print them.
unordered_map<char, string> huffmanCodes;
encode(root, "", huffmanCodes);
cout << "Huffman Codes are :\n" << '\n';
for (auto pair: huffmanCodes) {
// Char || Huffman Codes
cout << pair.first << " " << pair.second << '\n';
}
cout << "\nOriginal string was :\n" << text << '\n';
// print encoded string
string binStr = "";
for (char ch: text) {
binStr += huffmanCodes[ch];
}
cout << "\nEncoded string is :\n" << binStr << '\n';
cout<<endl;
// Calculating the size of input string in bits
int inputSizeInBits = text.length()*8;
cout<< "Size of input string in bits: " << inputSizeInBits << " bits"<<endl;
// Calculating the encoded binary string size in bits
int encodedSizeInBits = binStr.length();
cout << "Encoded string size in bits: " << encodedSizeInBits << " bits" << endl;
double compressionFactor = calculateCompressionFactor(inputSizeInBits,encodedSizeInBits);
cout<< "Compression Percentage: " << compressionFactor << " %"<<endl;
// Traverse the Huffman tree to decode the encoded string to get the orginal string.
int index = -1;
cout << "\nDecoded string is: \n";
string decodedString;
while (index < (int)binStr.size() - 2) {
decode(root, index, binStr,decodedString);
}
// Using hamming distance, lets find the difference between the original string and the decoded string.
// To check whether there is any loss in compression or not.
int lossOfCompression = hammingDistance(text, decodedString);
cout<<endl<<endl;
cout <<"Lost bits due to Compression (Hamming Distance): " << lossOfCompression << " bits" << endl;
if(!lossOfCompression){
cout << "Which means it's a lossless Compression.";
}
}
// Huffman coding algorithm
int main()
{
string text;
getline(cin, text);
HuffmanCompression(text);
return 0;
}