A tanfolyam kezdete előtt
A Huffman kódolás egy adattömörítési algoritmus, amely megfogalmazza a fájltömörítés alapötletét. Ebben a cikkben a rögzített és változó hosszúságú kódolásról, az egyedileg dekódolható kódokról, az előtagszabályokról és a Huffman-fa felépítéséről lesz szó.
Tudjuk, hogy minden karakter 0-ból és 1-ből álló sorozatként van tárolva, és 8 bitet foglal el. Ezt fix hosszúságú kódolásnak nevezik, mivel minden karakter ugyanazt a fix számú bitet használja a tároláshoz.
Tegyük fel, hogy szöveget kapunk. Hogyan csökkenthetjük egyetlen karakter tárolásához szükséges helyet?
A fő ötlet a változó hosszúságú kódolás. Használhatjuk azt a tényt, hogy a szöveg egyes karakterei gyakrabban fordulnak elő, mint mások (
Hogyan lehet a bitsorozat ismeretében egyértelműen dekódolni?
Vegye figyelembe a vonalat "abacdab". 8 karakterből áll, és fix hosszúságú kódolásakor 64 bitre lesz szüksége a tároláshoz. Vegye figyelembe, hogy a szimbólum gyakorisága "a", "b", "c" и "D" rendre 4, 2, 1, 1. Próbáljuk elképzelni "abacdab" kevesebb bitet, kihasználva azt a tényt "nak nek" gyakrabban fordul elő, mint "B"És "B" gyakrabban fordul elő, mint "c" и "D". Kezdjük a kódolással "nak nek" egy bittel egyenlő 0, "B" hozzárendelünk egy kétbites 11-es kódot, és három bittel 100 és 011 kódolunk "c" и "D".
Ennek eredményeként a következőket kapjuk:
a
0
b
11
c
100
d
011
Tehát a vonal "abacdab" mint kódoljuk 00110100011011 (0|0|11|0|100|011|0|11)a fenti kódok segítségével. A fő probléma azonban a dekódolásban lesz. Amikor megpróbáljuk dekódolni a karakterláncot 00110100011011, kétértelmű eredményt kapunk, mivel ez a következőképpen ábrázolható:
0|011|0|100|011|0|11 adacdab
0|0|11|0|100|0|11|011 aabacabd
0|011|0|100|0|11|0|11 adacabab
...
stb
Ennek a kétértelműségnek a elkerülése érdekében gondoskodnunk kell arról, hogy a kódolásunk megfeleljen egy olyan koncepciónak, mint pl előtag szabály, ami viszont azt jelenti, hogy a kódok csak egyetlen egyedi módon dekódolhatók. Az előtagszabály biztosítja, hogy egyetlen kód sem legyen másik kód előtagja. Kód alatt egy adott karakter megjelenítésére használt biteket értjük. A fenti példában 0 egy előtag 011, ami sérti az előtagszabályt. Tehát, ha kódjaink megfelelnek az előtagszabálynak, akkor egyedileg tudjuk dekódolni (és fordítva).
Nézzük újra a fenti példát. Ezúttal a szimbólumokhoz rendelünk hozzá "a", "b", "c" и "D" kódok, amelyek megfelelnek az előtagszabálynak.
a
0
b
10
c
110
d
111
Ezzel a kódolással a karakterlánc "abacdab" ként lesz kódolva 00100100011010 (0|0|10|0|100|011|0|10). De a 00100100011010 máris képesek leszünk egyértelműen dekódolni és visszatérni eredeti karakterláncunkhoz "abacdab".
Huffman kódolás
Most, hogy foglalkoztunk a változó hosszúságú kódolással és az előtag-szabállyal, beszéljünk a Huffman-kódolásról.
A módszer bináris fák létrehozásán alapul. Ebben a csomópont lehet végleges vagy belső. Kezdetben minden csomópontot levélnek (terminálnak) tekintünk, amely magát a szimbólumot és annak súlyát (vagyis az előfordulás gyakoriságát) reprezentálja. A belső csomópontok tartalmazzák a karakter súlyát, és két leszármazott csomópontra utalnak. Általános megegyezés szerint, kicsit "0" a bal ág követését jelenti, és "1" - jobbra. teljes fában N levelek és N-1 belső csomópontok. Javasoljuk, hogy a Huffman-fa összeállításakor a fel nem használt szimbólumokat dobja el az optimális hosszúságú kódok elérése érdekében.
A Huffman-fa felépítéséhez prioritási sort fogunk használni, ahol a legalacsonyabb frekvenciájú csomópont kap a legmagasabb prioritást. Az építés lépéseit az alábbiakban ismertetjük:
- Hozzon létre egy levél csomópontot minden karakterhez, és adja hozzá őket a prioritási sorhoz.
- Amíg egynél több lap van a sorban, tegye a következőket:
- Távolítsa el a két legmagasabb prioritású (legalacsonyabb frekvenciájú) csomópontot a sorból;
- Hozzon létre egy új belső csomópontot, ahol ez a két csomópont gyermek lesz, és az előfordulási gyakoriság megegyezik e két csomópont gyakoriságának összegével.
- Adjon hozzá egy új csomópontot a prioritási sorhoz.
- Az egyetlen megmaradt csomópont a gyökér lesz, és ezzel befejeződik a fa felépítése.
Képzeljük el, hogy van egy szövegünk, amely csak karakterekből áll "a", "b", "c", "d" и "és", és előfordulási gyakoriságuk 15, 7, 6, 6 és 5. Az alábbiakban az algoritmus lépéseit tükröző illusztrációk találhatók.
A gyökértől bármely végcsomópontig vezető útvonal tárolja az optimális előtagkódot (más néven Huffman-kódot), amely megfelel az adott végcsomóponthoz társított karakternek.
Huffman fa
Az alábbiakban megtalálja a Huffman tömörítési algoritmus megvalósítását C++ és Java nyelven:
#include <iostream>
#include <string>
#include <queue>
#include <unordered_map>
using namespace std;
// A Tree node
struct Node
{
char ch;
int freq;
Node *left, *right;
};
// Function to allocate a new tree node
Node* getNode(char ch, int freq, Node* left, Node* right)
{
Node* node = new Node();
node->ch = ch;
node->freq = freq;
node->left = left;
node->right = right;
return node;
}
// Comparison object to be used to order the heap
struct comp
{
bool operator()(Node* l, Node* r)
{
// highest priority item has lowest frequency
return l->freq > r->freq;
}
};
// traverse the Huffman Tree and store Huffman Codes
// in a map.
void encode(Node* root, string str,
unordered_map<char, string> &huffmanCode)
{
if (root == nullptr)
return;
// found a leaf node
if (!root->left && !root->right) {
huffmanCode[root->ch] = str;
}
encode(root->left, str + "0", huffmanCode);
encode(root->right, str + "1", huffmanCode);
}
// traverse the Huffman Tree and decode the encoded string
void decode(Node* root, int &index, string str)
{
if (root == nullptr) {
return;
}
// found a leaf node
if (!root->left && !root->right)
{
cout << root->ch;
return;
}
index++;
if (str[index] =='0')
decode(root->left, index, str);
else
decode(root->right, index, str);
}
// Builds Huffman Tree and decode given input text
void buildHuffmanTree(string text)
{
// count frequency of appearance of each character
// and store it in a map
unordered_map<char, int> freq;
for (char ch: text) {
freq[ch]++;
}
// Create a priority queue to store live nodes of
// Huffman tree;
priority_queue<Node*, vector<Node*>, comp> pq;
// Create a leaf node for each character and add it
// to the priority queue.
for (auto pair: freq) {
pq.push(getNode(pair.first, pair.second, nullptr, nullptr));
}
// do till there is more than one node in the queue
while (pq.size() != 1)
{
// Remove the two nodes of highest priority
// (lowest frequency) from the queue
Node *left = pq.top(); pq.pop();
Node *right = pq.top(); pq.pop();
// Create a new internal node with these two nodes
// as children and with frequency equal to the sum
// of the two nodes' frequencies. Add the new node
// to the priority queue.
int sum = left->freq + right->freq;
pq.push(getNode('', sum, left, right));
}
// root stores pointer to root of Huffman Tree
Node* root = pq.top();
// traverse the Huffman Tree and store Huffman Codes
// in a map. Also prints them
unordered_map<char, string> huffmanCode;
encode(root, "", huffmanCode);
cout << "Huffman Codes are :n" << 'n';
for (auto pair: huffmanCode) {
cout << pair.first << " " << pair.second << 'n';
}
cout << "nOriginal string was :n" << text << 'n';
// print encoded string
string str = "";
for (char ch: text) {
str += huffmanCode[ch];
}
cout << "nEncoded string is :n" << str << 'n';
// traverse the Huffman Tree again and this time
// decode the encoded string
int index = -1;
cout << "nDecoded string is: n";
while (index < (int)str.size() - 2) {
decode(root, index, str);
}
}
// Huffman coding algorithm
int main()
{
string text = "Huffman coding is a data compression algorithm.";
buildHuffmanTree(text);
return 0;
}
import java.util.HashMap;
import java.util.Map;
import java.util.PriorityQueue;
// A Tree node
class Node
{
char ch;
int freq;
Node left = null, right = null;
Node(char ch, int freq)
{
this.ch = ch;
this.freq = freq;
}
public Node(char ch, int freq, Node left, Node right) {
this.ch = ch;
this.freq = freq;
this.left = left;
this.right = right;
}
};
class Huffman
{
// traverse the Huffman Tree and store Huffman Codes
// in a map.
public static void encode(Node root, String str,
Map<Character, String> huffmanCode)
{
if (root == null)
return;
// found a leaf node
if (root.left == null && root.right == null) {
huffmanCode.put(root.ch, str);
}
encode(root.left, str + "0", huffmanCode);
encode(root.right, str + "1", huffmanCode);
}
// traverse the Huffman Tree and decode the encoded string
public static int decode(Node root, int index, StringBuilder sb)
{
if (root == null)
return index;
// found a leaf node
if (root.left == null && root.right == null)
{
System.out.print(root.ch);
return index;
}
index++;
if (sb.charAt(index) == '0')
index = decode(root.left, index, sb);
else
index = decode(root.right, index, sb);
return index;
}
// Builds Huffman Tree and huffmanCode and decode given input text
public static void buildHuffmanTree(String text)
{
// count frequency of appearance of each character
// and store it in a map
Map<Character, Integer> freq = new HashMap<>();
for (int i = 0 ; i < text.length(); i++) {
if (!freq.containsKey(text.charAt(i))) {
freq.put(text.charAt(i), 0);
}
freq.put(text.charAt(i), freq.get(text.charAt(i)) + 1);
}
// Create a priority queue to store live nodes of Huffman tree
// Notice that highest priority item has lowest frequency
PriorityQueue<Node> pq = new PriorityQueue<>(
(l, r) -> l.freq - r.freq);
// Create a leaf node for each character and add it
// to the priority queue.
for (Map.Entry<Character, Integer> entry : freq.entrySet()) {
pq.add(new Node(entry.getKey(), entry.getValue()));
}
// do till there is more than one node in the queue
while (pq.size() != 1)
{
// Remove the two nodes of highest priority
// (lowest frequency) from the queue
Node left = pq.poll();
Node right = pq.poll();
// Create a new internal node with these two nodes as children
// and with frequency equal to the sum of the two nodes
// frequencies. Add the new node to the priority queue.
int sum = left.freq + right.freq;
pq.add(new Node('', sum, left, right));
}
// root stores pointer to root of Huffman Tree
Node root = pq.peek();
// traverse the Huffman tree and store the Huffman codes in a map
Map<Character, String> huffmanCode = new HashMap<>();
encode(root, "", huffmanCode);
// print the Huffman codes
System.out.println("Huffman Codes are :n");
for (Map.Entry<Character, String> entry : huffmanCode.entrySet()) {
System.out.println(entry.getKey() + " " + entry.getValue());
}
System.out.println("nOriginal string was :n" + text);
// print encoded string
StringBuilder sb = new StringBuilder();
for (int i = 0 ; i < text.length(); i++) {
sb.append(huffmanCode.get(text.charAt(i)));
}
System.out.println("nEncoded string is :n" + sb);
// traverse the Huffman Tree again and this time
// decode the encoded string
int index = -1;
System.out.println("nDecoded string is: n");
while (index < sb.length() - 2) {
index = decode(root, index, sb);
}
}
public static void main(String[] args)
{
String text = "Huffman coding is a data compression algorithm.";
buildHuffmanTree(text);
}
}
Megjegyzés: a bemeneti karakterlánc által használt memória 47 * 8 = 376 bit, a kódolt karakterlánc pedig csak 194 bit, azaz. az adatok körülbelül 48%-kal vannak tömörítve. A fenti C++ programban a string osztályt használjuk a kódolt karakterlánc tárolására, hogy a program olvasható legyen.
Mivel a hatékony prioritási sor adatstruktúrákhoz beszúrásonként van szükség O(log(N)) időben, de egy teljes bináris fában N levelek jelen vannak 2N-1 csomópontokat, és a Huffman-fa egy teljes bináris fa, akkor az algoritmus befut O(Nlog(N)) idő, hol N - Karakterek.
Forrás:
Forrás: will.com