forked from Devika-j/huffman-coding
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.cpp
More file actions
108 lines (95 loc) · 2.42 KB
/
main.cpp
File metadata and controls
108 lines (95 loc) · 2.42 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
#include <cstring>
#include <iostream>
#include <unordered_map>
#include "dependencies/conversions.hpp"
#include "dependencies/graphics.hpp"
#include "dependencies/map.hpp"
#include "dependencies/tree.hpp"
#ifdef _WIN32
#include <windows.h>
#else
#include <unistd.h>
#endif
using namespace std;
unordered_map<char, int> freq, temp;
int totcount = 0;
unordered_map<char, string> freq2;
void compressed(string s, hufftree *root)
{
gotoxy(0, 10);
cout << "Size after compression is: " << sizeof(root) << " bits";
cout << "\nCompressed encoded message is:" << endl;
for (int i = 0; s[i] != '\0'; i++)
cout << freq2[s[i]];
gotoxy(0, 15);
cout << "Compression factor: " << totcount/sizeof(root);
}
char find_key_value(int data)
{
for (auto i : temp)
if (i.second == data)
return i.first;
}
void encode(hufftree *root, string s = "\0")
{
if (root->left == NULL && root->right == NULL)
{
freq2[find_key_value(root->data)] = s;
return;
}
else if (root->left == NULL)
encode(root->right, s + "1");
else if (root->right == NULL)
encode(root->left, s + "0");
else
{
encode(root->right, s + "1");
encode(root->left, s + "0");
}
}
hufftree *implement_tree()
{
hufftree *root = new hufftree(totcount);
hufftree *curr = root;
int temp_count = freq.size();
for (int i = 0; i < temp_count; i++)
{
char ch = max_freq(freq);
int value = freq[ch];
freq.erase(ch);
temp[ch] = value;
hufftree *node = new hufftree(temp[ch]);
curr->right = node;
node = new hufftree(curr->data - temp[ch]);
curr->left = node;
curr = curr->left;
}
return root;
}
void calcfreq(string input)
{
for (int i = 0; i < input.size(); i++)
freq[input[i]]++;
}
int main()
{
string input;
cout << "Enter the text to be compressed:" << endl;
getline(cin, input);
system("cls");
cout << "Input Details ->" << endl;
cout << "Text : ";
for (int i = 0; input[i] != '\0'; i++)
cout << input[i];
for (int i = 0; input[i] != '\0'; i++)
totcount++;
cout << "\nSize of text : " << totcount << " bits" << endl;
strToBinary(input);
calcfreq(input);
hufftree *root = implement_tree();
encode(root); //Causing the program to exit instantly.
compressed(input, root);
int n;
cin >> n;
return 0;
}