-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhuffman.cpp
More file actions
59 lines (47 loc) · 1.62 KB
/
huffman.cpp
File metadata and controls
59 lines (47 loc) · 1.62 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
#include "huffman.h"
#include <tuple>
#include "binary_trie.h"
#include "priority_queue.h"
bool PointerCompare(const BinaryTrie::Pointer& lhs, const BinaryTrie::Pointer& rhs) {
return *lhs > *rhs;
}
CodeSizes HuffmanEncoding(const SymbolsCount& symbols_count) {
PriorityQueue<BinaryTrie::Pointer, decltype(PointerCompare)*> queue(PointerCompare);
queue.Reserve(symbols_count.size());
for (const auto& [key, count] : symbols_count) {
queue.Push(std::make_shared<BinaryTrie>(key, count));
}
while (queue.Size() > 1) {
BinaryTrie::Pointer left = queue.Top();
queue.Pop();
BinaryTrie::Pointer right = queue.Top();
queue.Pop();
BinaryTrie::Pointer node = std::make_shared<BinaryTrie>(left, right);
queue.Push(node);
}
BinaryTrie::Pointer root = queue.Top();
queue.Pop();
CodeSizes sizes;
sizes.reserve(symbols_count.size());
auto callback = [&](std::size_t, std::size_t size, Char key) { sizes.push_back(CodeSize{key, size}); };
root->Traverse(callback);
std::sort(sizes.begin(), sizes.end());
return sizes;
};
CodeTable CanonicalCodes(const CodeSizes& sizes) {
CodeTable codes;
std::size_t current_code = 0;
std::size_t current_size = 1;
for (const auto& [key, size] : sizes) {
while (current_size < size) {
current_code <<= 1;
++current_size;
}
codes[key] = Code{current_code, current_size};
++current_code;
}
return codes;
}
bool CodeSize::operator<(const CodeSize& other) const {
return std::tie(size, key) < std::tie(other.size, other.key);
}