|
ADS
Algorithms and Data Structures
|
The code of Huffman (reality check of section 14.4): a prefix code, no code being a prefix of another one, so that a text can be decoded, of least length for the frequencies of the characters. More...
#include "ADS/Contract.h"#include "ADS/priority/HeapPriorityQueue.h"#include <algorithm>#include <cstddef>#include <map>#include <stdexcept>#include <string>#include <vector>#include "ADS/string/impl/Huffman.tpp"Go to the source code of this file.
Namespaces | |
| namespace | ADS |
Functions | |
| template<class C, class F> | |
| std::map< C, std::string > | ADS::huffman (const std::map< C, F > &freq) |
| the codes of Huffman of the characters with the given frequencies, at least one; a single character gets the code 0 | |
| template<class C> | |
| std::string | ADS::encode (const std::basic_string< C > &text, const std::map< C, std::string > &code) |
| the text encoded by the codes, the code of each character in turn | |
| template<class C> | |
| std::basic_string< C > | ADS::decode (const std::string &bits, const std::map< C, std::string > &code) |
| the bits decoded by the codes, a prefix code | |
The code of Huffman (reality check of section 14.4): a prefix code, no code being a prefix of another one, so that a text can be decoded, of least length for the frequencies of the characters.
The characters go into a min-heap by frequency; the two least frequent ones, \( c_1 \) and \( c_2 \), are replaced by a new virtual character of frequency \( f_1 + f_2 \), whose children in a binary tree are \( c_1 \) and \( c_2 \); after \( n - 1 \) steps the root is left, and the code of a character is the path from the root to its leaf, 0 to the left and 1 to the right, in \( O( n \log n ) \) time. The least frequent characters get the longest codes.
The contracts [see Contract.h]: huffman() needs at least one character and no negative frequency, and gives a prefix-free code of each character (checked at the level of the audits); encode() needs a code for each character of the text, and decode() bits that are a concatenation of codes. The operations are defined in Huffman.tpp.