-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmaain.cpp
More file actions
144 lines (97 loc) · 2.85 KB
/
maain.cpp
File metadata and controls
144 lines (97 loc) · 2.85 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
#include <iostream>
#include <queue>
#include <unordered_map>
#include <string>
using namespace std;
//Huffman tree node
struct MinHeapNode{
char data;
int freq;
MinHeapNode *left, *right;
MinHeapNode (char data, int freq){
left = right = NULL;
this -> data = data;
this -> freq = freq;
}
};
//struct compare
struct compare{
bool operator()(MinHeapNode *a, MinHeapNode *b){
return (a->freq > b->freq);
}
};
//printing huffman code
void printcodes(MinHeapNode* root, unordered_map<char,string>&huffmancodes, string str =" ") {
if (!root ){
return;
}
if(root->data != '\0'){
huffmancodes[root->data] = str;
}
printcodes(root->left, huffmancodes,str+'0');
printcodes(root->right, huffmancodes, str+'1');
}
//build huffman tree
MinHeapNode* generatehuffmancode(const unordered_map<char, int> freq){
//create min heap
struct MinHeapNode *left, *right, *top;
priority_queue<MinHeapNode*, vector<MinHeapNode*>,compare>minheap;
//creat node for each
for(const auto&entry : freq)
minheap.push(new MinHeapNode(entry.first, entry.second));
//itereate till 1
while(minheap.size() > 1){
left = minheap.top();
minheap.pop();
right = minheap.top();
minheap.pop();
top= new MinHeapNode('\0', left->freq + right->freq);
top->left = left;
top->right = right;
minheap.push(top);
}
//print node
return(minheap.top());
}
//encode
string encoded(const string& data, const unordered_map<char, string>& huffmancodes) {
string encoded;
for(char ch: data){
encoded+=huffmancodes.at(ch);
}
return encoded;
}
//decode
string decoded(const string& encoded, MinHeapNode* root){
string decoded;
MinHeapNode* curr=root;
for(char ch:encoded){
if(ch =='0'){
curr = curr->left;
}
else if(ch =='1'){
curr = curr->right;
}
if(curr->data !='\0'){
decoded+=curr->data;
curr=root;
}
}
return decoded;
}
int main(){
string input = "Hello, World!";
unordered_map<char,int>FreqTable;
for(char ch:input){
FreqTable[ch]++;
}
MinHeapNode* HuffmanTree = generatehuffmancode(FreqTable);
unordered_map<char,string> huffmancodes;
printcodes(HuffmanTree, huffmancodes);
//string encode
string encodedData= encoded(input,huffmancodes);
string decodedData= decoded(encodedData,HuffmanTree);
cout << "Input: " << input << endl;
cout << "Encoded data: " << encodedData << endl;
cout << "Decoded data: " << decodedData << endl;
}