forked from koolkarthik97/Graphics
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathHuffmanEncoding.cpp
More file actions
95 lines (73 loc) · 2.46 KB
/
Copy pathHuffmanEncoding.cpp
File metadata and controls
95 lines (73 loc) · 2.46 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
#include<bits/stdc++.h>
using namespace std;
struct MinHeapNode{
char data;
unsigned freq;
MinHeapNode *left, *right;
MinHeapNode(char data, unsigned freq){
left = right = NULL;
this->data = data;
this->freq = freq;
}
};
struct compare{
bool operator()(MinHeapNode *l, MinHeapNode *r){
return (l->freq > r->freq);
}
};
void printCodes(struct MinHeapNode *root, string str, map<char, string> &codeMap){
if(!root)
return;
if(root->data != '$'){
cout << root->data << " : " << str << endl;
codeMap[root->data] = str;
}
printCodes(root->left, str + "0", codeMap);
printCodes(root->right, str + "1", codeMap);
}
map<char, string> HuffmanCode(char data[], int freq[], int size){
struct MinHeapNode *left, *right, *top;
map<char, string> codeMap;
priority_queue<MinHeapNode *, vector<MinHeapNode*>, compare> minHeap;
for(int i=0;i<size; i++)
minHeap.push(new MinHeapNode(data[i] , freq[i]));
while(minHeap.size() != 1){
left = minHeap.top();
minHeap.pop();
right = minHeap.top();
minHeap.pop();
top = new MinHeapNode('$', left->freq + right->freq);
top->left = left;
top->right = right;
minHeap.push(top);
}
printCodes(minHeap.top(), "", codeMap);
return codeMap;
}
int main(){
string testStr("this is an example of a huffman tree");
map<char, int>inputMap;
char arr[100];
int freq[100];
for(int i=0;i<testStr.size(); i++)
inputMap[testStr[i]] += 1;
//arr = (char *) malloc(inputMap.size());
//freq = (int *) malloc(inputMap.size() * sizeof(int));
int i=0;
for(map<char, int>::iterator iter = inputMap.begin(); iter != inputMap.end(); iter++){
cout << iter->first << " is " << iter->second << endl;
arr[i] = (*iter).first;
freq[i] = (*iter).second;
i++;
}
int size = i;
map<char, string> codeMap;
codeMap = HuffmanCode(arr, freq, size);
string codeStr = "";
for(int i=0; i<testStr.size(); i++){
codeStr += codeMap[testStr[i]];
codeStr += " ";
}
cout << "The Final Output is " << codeStr << endl;
return 0;
}