23 std::shared_ptr<node> left;
24 std::shared_ptr<node> right;
25 node(std::string ID,
double weight)
26 : ID(ID), weight(weight), left(
nullptr), right(
nullptr) {}
30 std::shared_ptr<node> root;
31 std::unordered_map<char, double> appearances;
32 std::priority_queue<std::pair<double, std::shared_ptr<node>>,
33 std::vector<std::pair<double, std::shared_ptr<node>>>,
34 std::greater<std::pair<double, std::shared_ptr<node>>>>
36 std::unordered_map<char, double> map_weights;
45 explicit huffman(std::vector<std::string> v = {}, int64_t MAX_DEPTH = 10)
46 : root(nullptr), MAX_DEPTH(MAX_DEPTH) {
47 for (std::string& x : v) {
61 while (_weights.size() != 1) {
62 auto first_node = _weights.top();
64 auto second_node = _weights.top();
66 std::shared_ptr<node> nn =
67 std::make_shared<node>(first_node.second->ID + second_node.second->ID,
68 first_node.first + second_node.first);
69 nn->right = second_node.second;
70 nn->left = first_node.second;
71 _weights.push({nn->weight, nn});
73 root = _weights.top().second;
80 inline std::unordered_map<std::string, std::string>
decode() {
81 std::vector<int> v(MAX_DEPTH);
83 std::unordered_map<std::string, std::string> decoded;
84 _decode(root, v, top, decoded);
89 void compute_weights() {
90 for (
auto& x : appearances) {
91 std::string curr =
"";
93 std::shared_ptr<node> nn = std::make_shared<node>(curr, x.second / _size);
94 _weights.push({x.second / _size, nn});
95 map_weights[x.first] = x.second / _size;
99 void _decode(std::shared_ptr<node> root, std::vector<int> arr,
int top,
100 std::unordered_map<std::string, std::string>& decoded) {
103 _decode(root->left, arr, top + 1, decoded);
107 _decode(root->right, arr, top + 1, decoded);
109 if (!root->left && !root->right) {
110 std::string ans =
"";
111 for (
int i = 0; i < top; i++) {
112 ans += std::to_string(arr[i]);
114 decoded[root->ID] = ans;
huffman(std::vector< std::string > v={}, int64_t MAX_DEPTH=10)
constructor for huffman class
Definition huffman_encoding.h:45