A-M baby
This commit is contained in:
parent
764da6cbbb
commit
db842d013d
19005 changed files with 197040 additions and 7 deletions
22
Task/Huffman-coding/0DESCRIPTION
Normal file
22
Task/Huffman-coding/0DESCRIPTION
Normal file
|
|
@ -0,0 +1,22 @@
|
|||
Huffman encoding is a way to assign binary codes to symbols that reduces the overall number of bits used to encode a typical string of those symbols.
|
||||
|
||||
For example, if you use letters as symbols and have details of the frequency of occurrence of those letters in typical strings, then you could just encode each letter with a fixed number of bits, such as in ASCII codes. You can do better than this by encoding more frequently occurring letters such as e and a, with smaller bit strings; and less frequently occurring letters such as q and x with longer bit strings.
|
||||
|
||||
Any string of letters will be encoded as a string of bits that are no-longer of the same length per letter. To successfully decode such as string, the smaller codes assigned to letters such as 'e' cannot occur as a prefix in the larger codes such as that for 'x'.
|
||||
:If you were to assign a code 01 for 'e' and code 011 for 'x', then if the bits to decode started as 011... then you would not know if you should decode an 'e' or an 'x'.
|
||||
|
||||
The Huffman coding scheme takes each symbol and its weight (or frequency of occurrence), and generates proper encodings for each symbol taking account of the weights of each symbol, so that higher weighted symbols have fewer bits in their encoding. (See the [[wp:Huffman_coding|WP article]] for more information).
|
||||
|
||||
A Huffman encoding can be computed by first creating a tree of nodes:
|
||||
|
||||
[[Image:Huffman_coding_example.jpg|right|250px]]
|
||||
# Create a leaf node for each symbol and add it to the [[priority queue]].
|
||||
# While there is more than one node in the queue:
|
||||
## Remove the node of highest priority (lowest probability) twice to get two nodes.
|
||||
## Create a new internal node with these two nodes as children and with probability equal to the sum of the two nodes' probabilities.
|
||||
## Add the new node to the queue.
|
||||
# The remaining node is the root node and the tree is complete.
|
||||
|
||||
Traverse the constructed binary tree from root to leaves assigning and accumulating a '0' for one branch and a '1' for the other at each node. The accumulated zeros and ones at each leaf constitute a Huffman encoding for those symbols and weights:
|
||||
|
||||
'''Using the characters and their frequency from the string ''"this is an example for huffman encoding"'', create a program to generate a Huffman encoding for each character as a table.'''
|
||||
2
Task/Huffman-coding/1META.yaml
Normal file
2
Task/Huffman-coding/1META.yaml
Normal file
|
|
@ -0,0 +1,2 @@
|
|||
---
|
||||
note: Compression
|
||||
83
Task/Huffman-coding/Ada/huffman-coding-1.ada
Normal file
83
Task/Huffman-coding/Ada/huffman-coding-1.ada
Normal file
|
|
@ -0,0 +1,83 @@
|
|||
with Ada.Containers.Indefinite_Ordered_Maps;
|
||||
with Ada.Containers.Ordered_Maps;
|
||||
with Ada.Finalization;
|
||||
generic
|
||||
type Symbol_Type is private;
|
||||
with function "<" (Left, Right : Symbol_Type) return Boolean is <>;
|
||||
with procedure Put (Item : Symbol_Type);
|
||||
type Symbol_Sequence is array (Positive range <>) of Symbol_Type;
|
||||
type Frequency_Type is private;
|
||||
with function "+" (Left, Right : Frequency_Type) return Frequency_Type
|
||||
is <>;
|
||||
with function "<" (Left, Right : Frequency_Type) return Boolean is <>;
|
||||
package Huffman is
|
||||
-- bits = booleans (true/false = 1/0)
|
||||
type Bit_Sequence is array (Positive range <>) of Boolean;
|
||||
Zero_Sequence : constant Bit_Sequence (1 .. 0) := (others => False);
|
||||
-- output the sequence
|
||||
procedure Put (Code : Bit_Sequence);
|
||||
|
||||
-- type for freqency map
|
||||
package Frequency_Maps is new Ada.Containers.Ordered_Maps
|
||||
(Element_Type => Frequency_Type,
|
||||
Key_Type => Symbol_Type);
|
||||
|
||||
type Huffman_Tree is private;
|
||||
-- create a huffman tree from frequency map
|
||||
procedure Create_Tree
|
||||
(Tree : out Huffman_Tree;
|
||||
Frequencies : Frequency_Maps.Map);
|
||||
-- encode a single symbol
|
||||
function Encode
|
||||
(Tree : Huffman_Tree;
|
||||
Symbol : Symbol_Type)
|
||||
return Bit_Sequence;
|
||||
-- encode a symbol sequence
|
||||
function Encode
|
||||
(Tree : Huffman_Tree;
|
||||
Symbols : Symbol_Sequence)
|
||||
return Bit_Sequence;
|
||||
-- decode a bit sequence
|
||||
function Decode
|
||||
(Tree : Huffman_Tree;
|
||||
Code : Bit_Sequence)
|
||||
return Symbol_Sequence;
|
||||
-- dump the encoding table
|
||||
procedure Dump_Encoding (Tree : Huffman_Tree);
|
||||
private
|
||||
-- type for encoding map
|
||||
package Encoding_Maps is new Ada.Containers.Indefinite_Ordered_Maps
|
||||
(Element_Type => Bit_Sequence,
|
||||
Key_Type => Symbol_Type);
|
||||
|
||||
type Huffman_Node;
|
||||
type Node_Access is access Huffman_Node;
|
||||
-- a node is either internal (left_child/right_child used)
|
||||
-- or a leaf (left_child/right_child are null)
|
||||
type Huffman_Node is record
|
||||
Frequency : Frequency_Type;
|
||||
Left_Child : Node_Access := null;
|
||||
Right_Child : Node_Access := null;
|
||||
Symbol : Symbol_Type;
|
||||
end record;
|
||||
-- create a leaf node
|
||||
function Create_Node
|
||||
(Symbol : Symbol_Type;
|
||||
Frequency : Frequency_Type)
|
||||
return Node_Access;
|
||||
-- create an internal node
|
||||
function Create_Node (Left, Right : Node_Access) return Node_Access;
|
||||
-- fill the encoding map
|
||||
procedure Fill
|
||||
(The_Node : Node_Access;
|
||||
Map : in out Encoding_Maps.Map;
|
||||
Prefix : Bit_Sequence);
|
||||
|
||||
-- huffman tree has a tree and an encoding map
|
||||
type Huffman_Tree is new Ada.Finalization.Controlled with record
|
||||
Tree : Node_Access := null;
|
||||
Map : Encoding_Maps.Map := Encoding_Maps.Empty_Map;
|
||||
end record;
|
||||
-- free memory after finalization
|
||||
overriding procedure Finalize (Object : in out Huffman_Tree);
|
||||
end Huffman;
|
||||
244
Task/Huffman-coding/Ada/huffman-coding-2.ada
Normal file
244
Task/Huffman-coding/Ada/huffman-coding-2.ada
Normal file
|
|
@ -0,0 +1,244 @@
|
|||
with Ada.Text_IO;
|
||||
with Ada.Unchecked_Deallocation;
|
||||
with Ada.Containers.Vectors;
|
||||
package body Huffman is
|
||||
package Node_Vectors is new Ada.Containers.Vectors
|
||||
(Element_Type => Node_Access,
|
||||
Index_Type => Positive);
|
||||
|
||||
function "<" (Left, Right : Node_Access) return Boolean is
|
||||
begin
|
||||
-- compare frequency
|
||||
if Left.Frequency < Right.Frequency then
|
||||
return True;
|
||||
elsif Right.Frequency < Left.Frequency then
|
||||
return False;
|
||||
end if;
|
||||
-- same frequency, choose leaf node
|
||||
if Left.Left_Child = null and then Right.Left_Child /= null then
|
||||
return True;
|
||||
elsif Left.Left_Child /= null and then Right.Left_Child = null then
|
||||
return False;
|
||||
end if;
|
||||
-- same frequency, same node type (internal/leaf)
|
||||
if Left.Left_Child /= null then
|
||||
-- for internal nodes, compare left children, then right children
|
||||
if Left.Left_Child < Right.Left_Child then
|
||||
return True;
|
||||
elsif Right.Left_Child < Left.Left_Child then
|
||||
return False;
|
||||
else
|
||||
return Left.Right_Child < Right.Right_Child;
|
||||
end if;
|
||||
else
|
||||
-- for leaf nodes, compare symbol
|
||||
return Left.Symbol < Right.Symbol;
|
||||
end if;
|
||||
end "<";
|
||||
package Node_Vector_Sort is new Node_Vectors.Generic_Sorting;
|
||||
|
||||
procedure Create_Tree
|
||||
(Tree : out Huffman_Tree;
|
||||
Frequencies : Frequency_Maps.Map) is
|
||||
Node_Queue : Node_Vectors.Vector := Node_Vectors.Empty_Vector;
|
||||
begin
|
||||
-- insert all leafs into the queue
|
||||
declare
|
||||
use Frequency_Maps;
|
||||
Position : Cursor := Frequencies.First;
|
||||
The_Node : Node_Access := null;
|
||||
begin
|
||||
while Position /= No_Element loop
|
||||
The_Node :=
|
||||
Create_Node
|
||||
(Symbol => Key (Position),
|
||||
Frequency => Element (Position));
|
||||
Node_Queue.Append (The_Node);
|
||||
Next (Position);
|
||||
end loop;
|
||||
end;
|
||||
-- sort by frequency (see "<")
|
||||
Node_Vector_Sort.Sort (Node_Queue);
|
||||
-- iterate over all elements
|
||||
while not Node_Queue.Is_Empty loop
|
||||
declare
|
||||
First : constant Node_Access := Node_Queue.First_Element;
|
||||
begin
|
||||
Node_Queue.Delete_First;
|
||||
-- if we only have one node left, it is the root node of the tree
|
||||
if Node_Queue.Is_Empty then
|
||||
Tree.Tree := First;
|
||||
else
|
||||
-- create new internal node with two smallest frequencies
|
||||
declare
|
||||
Second : constant Node_Access := Node_Queue.First_Element;
|
||||
begin
|
||||
Node_Queue.Delete_First;
|
||||
Node_Queue.Append (Create_Node (First, Second));
|
||||
end;
|
||||
Node_Vector_Sort.Sort (Node_Queue);
|
||||
end if;
|
||||
end;
|
||||
end loop;
|
||||
-- fill encoding map
|
||||
Fill (The_Node => Tree.Tree, Map => Tree.Map, Prefix => Zero_Sequence);
|
||||
end Create_Tree;
|
||||
|
||||
-- create leaf node
|
||||
function Create_Node
|
||||
(Symbol : Symbol_Type;
|
||||
Frequency : Frequency_Type)
|
||||
return Node_Access
|
||||
is
|
||||
Result : Node_Access := new Huffman_Node;
|
||||
begin
|
||||
Result.Frequency := Frequency;
|
||||
Result.Symbol := Symbol;
|
||||
return Result;
|
||||
end Create_Node;
|
||||
|
||||
-- create internal node
|
||||
function Create_Node (Left, Right : Node_Access) return Node_Access is
|
||||
Result : Node_Access := new Huffman_Node;
|
||||
begin
|
||||
Result.Frequency := Left.Frequency + Right.Frequency;
|
||||
Result.Left_Child := Left;
|
||||
Result.Right_Child := Right;
|
||||
return Result;
|
||||
end Create_Node;
|
||||
|
||||
-- fill encoding map
|
||||
procedure Fill
|
||||
(The_Node : Node_Access;
|
||||
Map : in out Encoding_Maps.Map;
|
||||
Prefix : Bit_Sequence) is
|
||||
begin
|
||||
if The_Node.Left_Child /= null then
|
||||
-- append false (0) for left child
|
||||
Fill (The_Node.Left_Child, Map, Prefix & False);
|
||||
-- append true (1) for right child
|
||||
Fill (The_Node.Right_Child, Map, Prefix & True);
|
||||
else
|
||||
-- leaf node reached, prefix = code for symbol
|
||||
Map.Insert (The_Node.Symbol, Prefix);
|
||||
end if;
|
||||
end Fill;
|
||||
|
||||
-- free memory after finalization
|
||||
overriding procedure Finalize (Object : in out Huffman_Tree) is
|
||||
procedure Free is new Ada.Unchecked_Deallocation
|
||||
(Name => Node_Access,
|
||||
Object => Huffman_Node);
|
||||
-- recursively free all nodes
|
||||
procedure Recursive_Free (The_Node : in out Node_Access) is
|
||||
begin
|
||||
-- free node if it is a leaf
|
||||
if The_Node.Left_Child = null then
|
||||
Free (The_Node);
|
||||
else
|
||||
-- free left and right child if node is internal
|
||||
Recursive_Free (The_Node.Left_Child);
|
||||
Recursive_Free (The_Node.Right_Child);
|
||||
-- free node afterwards
|
||||
Free (The_Node);
|
||||
end if;
|
||||
end Recursive_Free;
|
||||
begin
|
||||
-- recursively free root node
|
||||
Recursive_Free (Object.Tree);
|
||||
end Finalize;
|
||||
|
||||
-- encode single symbol
|
||||
function Encode
|
||||
(Tree : Huffman_Tree;
|
||||
Symbol : Symbol_Type)
|
||||
return Bit_Sequence
|
||||
is
|
||||
begin
|
||||
-- simply lookup in map
|
||||
return Tree.Map.Element (Symbol);
|
||||
end Encode;
|
||||
|
||||
-- encode symbol sequence
|
||||
function Encode
|
||||
(Tree : Huffman_Tree;
|
||||
Symbols : Symbol_Sequence)
|
||||
return Bit_Sequence
|
||||
is
|
||||
begin
|
||||
-- only one element
|
||||
if Symbols'Length = 1 then
|
||||
-- see above
|
||||
return Encode (Tree, Symbols (Symbols'First));
|
||||
else
|
||||
-- encode first element, append result of recursive call
|
||||
return Encode (Tree, Symbols (Symbols'First)) &
|
||||
Encode (Tree, Symbols (Symbols'First + 1 .. Symbols'Last));
|
||||
end if;
|
||||
end Encode;
|
||||
|
||||
-- decode a bit sequence
|
||||
function Decode
|
||||
(Tree : Huffman_Tree;
|
||||
Code : Bit_Sequence)
|
||||
return Symbol_Sequence
|
||||
is
|
||||
-- maximum length = code length
|
||||
Result : Symbol_Sequence (1 .. Code'Length);
|
||||
-- last used index of result
|
||||
Last : Natural := 0;
|
||||
The_Node : Node_Access := Tree.Tree;
|
||||
begin
|
||||
-- iterate over the code
|
||||
for I in Code'Range loop
|
||||
-- if current element is true, descent the right branch
|
||||
if Code (I) then
|
||||
The_Node := The_Node.Right_Child;
|
||||
else
|
||||
-- false: descend left branch
|
||||
The_Node := The_Node.Left_Child;
|
||||
end if;
|
||||
if The_Node.Left_Child = null then
|
||||
-- reached leaf node: append symbol to result
|
||||
Last := Last + 1;
|
||||
Result (Last) := The_Node.Symbol;
|
||||
-- reset current node to root
|
||||
The_Node := Tree.Tree;
|
||||
end if;
|
||||
end loop;
|
||||
-- return subset of result array
|
||||
return Result (1 .. Last);
|
||||
end Decode;
|
||||
|
||||
-- output a bit sequence
|
||||
procedure Put (Code : Bit_Sequence) is
|
||||
package Int_IO is new Ada.Text_IO.Integer_IO (Integer);
|
||||
begin
|
||||
for I in Code'Range loop
|
||||
if Code (I) then
|
||||
-- true = 1
|
||||
Int_IO.Put (1, 0);
|
||||
else
|
||||
-- false = 0
|
||||
Int_IO.Put (0, 0);
|
||||
end if;
|
||||
end loop;
|
||||
Ada.Text_IO.New_Line;
|
||||
end Put;
|
||||
|
||||
-- dump encoding map
|
||||
procedure Dump_Encoding (Tree : Huffman_Tree) is
|
||||
use type Encoding_Maps.Cursor;
|
||||
Position : Encoding_Maps.Cursor := Tree.Map.First;
|
||||
begin
|
||||
-- iterate map
|
||||
while Position /= Encoding_Maps.No_Element loop
|
||||
-- key
|
||||
Put (Encoding_Maps.Key (Position));
|
||||
Ada.Text_IO.Put (" = ");
|
||||
-- code
|
||||
Put (Encoding_Maps.Element (Position));
|
||||
Encoding_Maps.Next (Position);
|
||||
end loop;
|
||||
end Dump_Encoding;
|
||||
end Huffman;
|
||||
49
Task/Huffman-coding/Ada/huffman-coding-3.ada
Normal file
49
Task/Huffman-coding/Ada/huffman-coding-3.ada
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
with Ada.Text_IO;
|
||||
with Huffman;
|
||||
procedure Main is
|
||||
package Char_Natural_Huffman_Tree is new Huffman
|
||||
(Symbol_Type => Character,
|
||||
Put => Ada.Text_IO.Put,
|
||||
Symbol_Sequence => String,
|
||||
Frequency_Type => Natural);
|
||||
Tree : Char_Natural_Huffman_Tree.Huffman_Tree;
|
||||
Frequencies : Char_Natural_Huffman_Tree.Frequency_Maps.Map;
|
||||
Input_String : constant String :=
|
||||
"this is an example for huffman encoding";
|
||||
begin
|
||||
-- build frequency map
|
||||
for I in Input_String'Range loop
|
||||
declare
|
||||
use Char_Natural_Huffman_Tree.Frequency_Maps;
|
||||
Position : constant Cursor := Frequencies.Find (Input_String (I));
|
||||
begin
|
||||
if Position = No_Element then
|
||||
Frequencies.Insert (Key => Input_String (I), New_Item => 1);
|
||||
else
|
||||
Frequencies.Replace_Element
|
||||
(Position => Position,
|
||||
New_Item => Element (Position) + 1);
|
||||
end if;
|
||||
end;
|
||||
end loop;
|
||||
|
||||
-- create huffman tree
|
||||
Char_Natural_Huffman_Tree.Create_Tree
|
||||
(Tree => Tree,
|
||||
Frequencies => Frequencies);
|
||||
|
||||
-- dump encodings
|
||||
Char_Natural_Huffman_Tree.Dump_Encoding (Tree => Tree);
|
||||
|
||||
-- encode example string
|
||||
declare
|
||||
Code : constant Char_Natural_Huffman_Tree.Bit_Sequence :=
|
||||
Char_Natural_Huffman_Tree.Encode
|
||||
(Tree => Tree,
|
||||
Symbols => Input_String);
|
||||
begin
|
||||
Char_Natural_Huffman_Tree.Put (Code);
|
||||
Ada.Text_IO.Put_Line
|
||||
(Char_Natural_Huffman_Tree.Decode (Tree => Tree, Code => Code));
|
||||
end;
|
||||
end Main;
|
||||
53
Task/Huffman-coding/BBC-BASIC/huffman-coding.bbc
Normal file
53
Task/Huffman-coding/BBC-BASIC/huffman-coding.bbc
Normal file
|
|
@ -0,0 +1,53 @@
|
|||
INSTALL @lib$+"SORTSALIB"
|
||||
SortUp% = FN_sortSAinit(0,0) : REM Ascending
|
||||
SortDn% = FN_sortSAinit(1,0) : REM Descending
|
||||
|
||||
Text$ = "this is an example for huffman encoding"
|
||||
|
||||
DIM tree{(127) ch&, num%, lkl%, lkr%}
|
||||
FOR i% = 1 TO LEN(Text$)
|
||||
c% = ASCMID$(Text$,i%)
|
||||
tree{(c%)}.ch& = c%
|
||||
tree{(c%)}.num% += 1
|
||||
NEXT
|
||||
|
||||
C% = DIM(tree{()},1) + 1
|
||||
CALL SortDn%, tree{()}, tree{(0)}.num%
|
||||
FOR i% = 0 TO DIM(tree{()},1)
|
||||
IF tree{(i%)}.num% = 0 EXIT FOR
|
||||
NEXT
|
||||
size% = i%
|
||||
|
||||
linked% = 0
|
||||
REPEAT
|
||||
C% = size%
|
||||
CALL SortUp%, tree{()}, tree{(0)}.num%
|
||||
i% = 0 : WHILE tree{(i%)}.lkl% OR tree{(i%)}.lkr% i% += 1 : ENDWHILE
|
||||
tree{(i%)}.lkl% = size%
|
||||
j% = 0 : WHILE tree{(j%)}.lkl% OR tree{(j%)}.lkr% j% += 1 : ENDWHILE
|
||||
tree{(j%)}.lkr% = size%
|
||||
linked% += 2
|
||||
tree{(size%)}.num% = tree{(i%)}.num% + tree{(j%)}.num%
|
||||
size% += 1
|
||||
UNTIL linked% = (size% - 1)
|
||||
|
||||
FOR i% = size% - 1 TO 0 STEP -1
|
||||
IF tree{(i%)}.ch& THEN
|
||||
h$ = ""
|
||||
j% = i%
|
||||
REPEAT
|
||||
CASE TRUE OF
|
||||
WHEN tree{(j%)}.lkl% <> 0:
|
||||
h$ = "0" + h$
|
||||
j% = tree{(j%)}.lkl%
|
||||
WHEN tree{(j%)}.lkr% <> 0:
|
||||
h$ = "1" + h$
|
||||
j% = tree{(j%)}.lkr%
|
||||
OTHERWISE:
|
||||
EXIT REPEAT
|
||||
ENDCASE
|
||||
UNTIL FALSE
|
||||
VDU tree{(i%)}.ch& : PRINT " " h$
|
||||
ENDIF
|
||||
NEXT
|
||||
END
|
||||
115
Task/Huffman-coding/C++/huffman-coding.cpp
Normal file
115
Task/Huffman-coding/C++/huffman-coding.cpp
Normal file
|
|
@ -0,0 +1,115 @@
|
|||
#include <iostream>
|
||||
#include <queue>
|
||||
#include <map>
|
||||
#include <climits> // for CHAR_BIT
|
||||
#include <iterator>
|
||||
#include <algorithm>
|
||||
|
||||
const int UniqueSymbols = 1 << CHAR_BIT;
|
||||
const char* SampleString = "this is an example for huffman encoding";
|
||||
|
||||
typedef std::vector<bool> HuffCode;
|
||||
typedef std::map<char, HuffCode> HuffCodeMap;
|
||||
|
||||
class INode
|
||||
{
|
||||
public:
|
||||
const int f;
|
||||
|
||||
virtual ~INode() {}
|
||||
|
||||
protected:
|
||||
INode(int f) : f(f) {}
|
||||
};
|
||||
|
||||
class InternalNode : public INode
|
||||
{
|
||||
public:
|
||||
INode *const left;
|
||||
INode *const right;
|
||||
|
||||
InternalNode(INode* c0, INode* c1) : INode(c0->f + c1->f), left(c0), right(c1) {}
|
||||
~InternalNode()
|
||||
{
|
||||
delete left;
|
||||
delete right;
|
||||
}
|
||||
};
|
||||
|
||||
class LeafNode : public INode
|
||||
{
|
||||
public:
|
||||
const char c;
|
||||
|
||||
LeafNode(int f, char c) : INode(f), c(c) {}
|
||||
};
|
||||
|
||||
struct NodeCmp
|
||||
{
|
||||
bool operator()(const INode* lhs, const INode* rhs) const { return lhs->f > rhs->f; }
|
||||
};
|
||||
|
||||
INode* BuildTree(const int (&frequencies)[UniqueSymbols])
|
||||
{
|
||||
std::priority_queue<INode*, std::vector<INode*>, NodeCmp> trees;
|
||||
|
||||
for (int i = 0; i < UniqueSymbols; ++i)
|
||||
{
|
||||
if(frequencies[i] != 0)
|
||||
trees.push(new LeafNode(frequencies[i], (char)i));
|
||||
}
|
||||
while (trees.size() > 1)
|
||||
{
|
||||
INode* childR = trees.top();
|
||||
trees.pop();
|
||||
|
||||
INode* childL = trees.top();
|
||||
trees.pop();
|
||||
|
||||
INode* parent = new InternalNode(childR, childL);
|
||||
trees.push(parent);
|
||||
}
|
||||
return trees.top();
|
||||
}
|
||||
|
||||
void GenerateCodes(const INode* node, const HuffCode& prefix, HuffCodeMap& outCodes)
|
||||
{
|
||||
if (const LeafNode* lf = dynamic_cast<const LeafNode*>(node))
|
||||
{
|
||||
outCodes[lf->c] = prefix;
|
||||
}
|
||||
else if (const InternalNode* in = dynamic_cast<const InternalNode*>(node))
|
||||
{
|
||||
HuffCode leftPrefix = prefix;
|
||||
leftPrefix.push_back(false);
|
||||
GenerateCodes(in->left, leftPrefix, outCodes);
|
||||
|
||||
HuffCode rightPrefix = prefix;
|
||||
rightPrefix.push_back(true);
|
||||
GenerateCodes(in->right, rightPrefix, outCodes);
|
||||
}
|
||||
}
|
||||
|
||||
int main()
|
||||
{
|
||||
// Build frequency table
|
||||
int frequencies[UniqueSymbols] = {0};
|
||||
const char* ptr = SampleString;
|
||||
while (*ptr != '\0')
|
||||
++frequencies[*ptr++];
|
||||
|
||||
INode* root = BuildTree(frequencies);
|
||||
|
||||
HuffCodeMap codes;
|
||||
GenerateCodes(root, HuffCode(), codes);
|
||||
delete root;
|
||||
|
||||
for (HuffCodeMap::const_iterator it = codes.begin(); it != codes.end(); ++it)
|
||||
{
|
||||
std::cout << it->first << " ";
|
||||
std::copy(it->second.begin(), it->second.end(),
|
||||
std::ostream_iterator<bool>(std::cout));
|
||||
std::cout << std::endl;
|
||||
}
|
||||
return 0;
|
||||
}
|
||||
314
Task/Huffman-coding/C-sharp/huffman-coding.cs
Normal file
314
Task/Huffman-coding/C-sharp/huffman-coding.cs
Normal file
|
|
@ -0,0 +1,314 @@
|
|||
using System;
|
||||
using System.Collections.Generic;
|
||||
|
||||
namespace Huffman_Encoding
|
||||
{
|
||||
public class PriorityQueue<T> where T : IComparable
|
||||
{
|
||||
protected List<T> LstHeap = new List<T>();
|
||||
|
||||
public virtual int Count
|
||||
{
|
||||
get { return LstHeap.Count; }
|
||||
}
|
||||
|
||||
public virtual void Add(T val)
|
||||
{
|
||||
LstHeap.Add(val);
|
||||
SetAt(LstHeap.Count - 1, val);
|
||||
UpHeap(LstHeap.Count - 1);
|
||||
}
|
||||
|
||||
public virtual T Peek()
|
||||
{
|
||||
if (LstHeap.Count == 0)
|
||||
{
|
||||
throw new IndexOutOfRangeException("Peeking at an empty priority queue");
|
||||
}
|
||||
|
||||
return LstHeap[0];
|
||||
}
|
||||
|
||||
public virtual T Pop()
|
||||
{
|
||||
if (LstHeap.Count == 0)
|
||||
{
|
||||
throw new IndexOutOfRangeException("Popping an empty priority queue");
|
||||
}
|
||||
|
||||
T valRet = LstHeap[0];
|
||||
|
||||
SetAt(0, LstHeap[LstHeap.Count - 1]);
|
||||
LstHeap.RemoveAt(LstHeap.Count - 1);
|
||||
DownHeap(0);
|
||||
return valRet;
|
||||
}
|
||||
|
||||
protected virtual void SetAt(int i, T val)
|
||||
{
|
||||
LstHeap[i] = val;
|
||||
}
|
||||
|
||||
protected bool RightSonExists(int i)
|
||||
{
|
||||
return RightChildIndex(i) < LstHeap.Count;
|
||||
}
|
||||
|
||||
protected bool LeftSonExists(int i)
|
||||
{
|
||||
return LeftChildIndex(i) < LstHeap.Count;
|
||||
}
|
||||
|
||||
protected int ParentIndex(int i)
|
||||
{
|
||||
return (i - 1) / 2;
|
||||
}
|
||||
|
||||
protected int LeftChildIndex(int i)
|
||||
{
|
||||
return 2 * i + 1;
|
||||
}
|
||||
|
||||
protected int RightChildIndex(int i)
|
||||
{
|
||||
return 2 * (i + 1);
|
||||
}
|
||||
|
||||
protected T ArrayVal(int i)
|
||||
{
|
||||
return LstHeap[i];
|
||||
}
|
||||
|
||||
protected T Parent(int i)
|
||||
{
|
||||
return LstHeap[ParentIndex(i)];
|
||||
}
|
||||
|
||||
protected T Left(int i)
|
||||
{
|
||||
return LstHeap[LeftChildIndex(i)];
|
||||
}
|
||||
|
||||
protected T Right(int i)
|
||||
{
|
||||
return LstHeap[RightChildIndex(i)];
|
||||
}
|
||||
|
||||
protected void Swap(int i, int j)
|
||||
{
|
||||
T valHold = ArrayVal(i);
|
||||
SetAt(i, LstHeap[j]);
|
||||
SetAt(j, valHold);
|
||||
}
|
||||
|
||||
protected void UpHeap(int i)
|
||||
{
|
||||
while (i > 0 && ArrayVal(i).CompareTo(Parent(i)) > 0)
|
||||
{
|
||||
Swap(i, ParentIndex(i));
|
||||
i = ParentIndex(i);
|
||||
}
|
||||
}
|
||||
|
||||
protected void DownHeap(int i)
|
||||
{
|
||||
while (i >= 0)
|
||||
{
|
||||
int iContinue = -1;
|
||||
|
||||
if (RightSonExists(i) && Right(i).CompareTo(ArrayVal(i)) > 0)
|
||||
{
|
||||
iContinue = Left(i).CompareTo(Right(i)) < 0 ? RightChildIndex(i) : LeftChildIndex(i);
|
||||
}
|
||||
else if (LeftSonExists(i) && Left(i).CompareTo(ArrayVal(i)) > 0)
|
||||
{
|
||||
iContinue = LeftChildIndex(i);
|
||||
}
|
||||
|
||||
if (iContinue >= 0 && iContinue < LstHeap.Count)
|
||||
{
|
||||
Swap(i, iContinue);
|
||||
}
|
||||
|
||||
i = iContinue;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
internal class HuffmanNode<T> : IComparable
|
||||
{
|
||||
internal HuffmanNode(double probability, T value)
|
||||
{
|
||||
Probability = probability;
|
||||
LeftSon = RightSon = Parent = null;
|
||||
Value = value;
|
||||
IsLeaf = true;
|
||||
}
|
||||
|
||||
internal HuffmanNode(HuffmanNode<T> leftSon, HuffmanNode<T> rightSon)
|
||||
{
|
||||
LeftSon = leftSon;
|
||||
RightSon = rightSon;
|
||||
Probability = leftSon.Probability + rightSon.Probability;
|
||||
leftSon.IsZero = true;
|
||||
rightSon.IsZero = false;
|
||||
leftSon.Parent = rightSon.Parent = this;
|
||||
IsLeaf = false;
|
||||
}
|
||||
|
||||
internal HuffmanNode<T> LeftSon { get; set; }
|
||||
internal HuffmanNode<T> RightSon { get; set; }
|
||||
internal HuffmanNode<T> Parent { get; set; }
|
||||
internal T Value { get; set; }
|
||||
internal bool IsLeaf { get; set; }
|
||||
|
||||
internal bool IsZero { get; set; }
|
||||
|
||||
internal int Bit
|
||||
{
|
||||
get { return IsZero ? 0 : 1; }
|
||||
}
|
||||
|
||||
internal bool IsRoot
|
||||
{
|
||||
get { return Parent == null; }
|
||||
}
|
||||
|
||||
internal double Probability { get; set; }
|
||||
|
||||
public int CompareTo(object obj)
|
||||
{
|
||||
return -Probability.CompareTo(((HuffmanNode<T>) obj).Probability);
|
||||
}
|
||||
}
|
||||
|
||||
public class Huffman<T> where T : IComparable
|
||||
{
|
||||
private readonly Dictionary<T, HuffmanNode<T>> _leafDictionary = new Dictionary<T, HuffmanNode<T>>();
|
||||
private readonly HuffmanNode<T> _root;
|
||||
|
||||
public Huffman(IEnumerable<T> values)
|
||||
{
|
||||
var counts = new Dictionary<T, int>();
|
||||
var priorityQueue = new PriorityQueue<HuffmanNode<T>>();
|
||||
int valueCount = 0;
|
||||
|
||||
foreach (T value in values)
|
||||
{
|
||||
if (!counts.ContainsKey(value))
|
||||
{
|
||||
counts[value] = 0;
|
||||
}
|
||||
counts[value]++;
|
||||
valueCount++;
|
||||
}
|
||||
|
||||
foreach (T value in counts.Keys)
|
||||
{
|
||||
var node = new HuffmanNode<T>((double) counts[value] / valueCount, value);
|
||||
priorityQueue.Add(node);
|
||||
_leafDictionary[value] = node;
|
||||
}
|
||||
|
||||
while (priorityQueue.Count > 1)
|
||||
{
|
||||
HuffmanNode<T> leftSon = priorityQueue.Pop();
|
||||
HuffmanNode<T> rightSon = priorityQueue.Pop();
|
||||
var parent = new HuffmanNode<T>(leftSon, rightSon);
|
||||
priorityQueue.Add(parent);
|
||||
}
|
||||
|
||||
_root = priorityQueue.Pop();
|
||||
_root.IsZero = false;
|
||||
}
|
||||
|
||||
public List<int> Encode(T value)
|
||||
{
|
||||
var returnValue = new List<int>();
|
||||
Encode(value, returnValue);
|
||||
return returnValue;
|
||||
}
|
||||
|
||||
public void Encode(T value, List<int> encoding)
|
||||
{
|
||||
if (!_leafDictionary.ContainsKey(value))
|
||||
{
|
||||
throw new ArgumentException("Invalid value in Encode");
|
||||
}
|
||||
HuffmanNode<T> nodeCur = _leafDictionary[value];
|
||||
var reverseEncoding = new List<int>();
|
||||
while (!nodeCur.IsRoot)
|
||||
{
|
||||
reverseEncoding.Add(nodeCur.Bit);
|
||||
nodeCur = nodeCur.Parent;
|
||||
}
|
||||
|
||||
reverseEncoding.Reverse();
|
||||
encoding.AddRange(reverseEncoding);
|
||||
}
|
||||
|
||||
public List<int> Encode(IEnumerable<T> values)
|
||||
{
|
||||
var returnValue = new List<int>();
|
||||
|
||||
foreach (T value in values)
|
||||
{
|
||||
Encode(value, returnValue);
|
||||
}
|
||||
return returnValue;
|
||||
}
|
||||
|
||||
public T Decode(List<int> bitString, ref int position)
|
||||
{
|
||||
HuffmanNode<T> nodeCur = _root;
|
||||
while (!nodeCur.IsLeaf)
|
||||
{
|
||||
if (position > bitString.Count)
|
||||
{
|
||||
throw new ArgumentException("Invalid bitstring in Decode");
|
||||
}
|
||||
nodeCur = bitString[position++] == 0 ? nodeCur.LeftSon : nodeCur.RightSon;
|
||||
}
|
||||
return nodeCur.Value;
|
||||
}
|
||||
|
||||
public List<T> Decode(List<int> bitString)
|
||||
{
|
||||
int position = 0;
|
||||
var returnValue = new List<T>();
|
||||
|
||||
while (position != bitString.Count)
|
||||
{
|
||||
returnValue.Add(Decode(bitString, ref position));
|
||||
}
|
||||
return returnValue;
|
||||
}
|
||||
}
|
||||
|
||||
internal class Program
|
||||
{
|
||||
private const string Example = "this is an example for huffman encoding";
|
||||
|
||||
private static void Main()
|
||||
{
|
||||
var huffman = new Huffman<char>(Example);
|
||||
List<int> encoding = huffman.Encode(Example);
|
||||
List<char> decoding = huffman.Decode(encoding);
|
||||
var outString = new string(decoding.ToArray());
|
||||
Console.WriteLine(outString == Example ? "Encoding/decoding worked" : "Encoding/Decoding failed");
|
||||
|
||||
var chars = new HashSet<char>(Example);
|
||||
foreach (char c in chars)
|
||||
{
|
||||
encoding = huffman.Encode(c);
|
||||
Console.Write("{0}: ", c);
|
||||
foreach (int bit in encoding)
|
||||
{
|
||||
Console.Write("{0}", bit);
|
||||
}
|
||||
Console.WriteLine();
|
||||
}
|
||||
Console.ReadKey();
|
||||
}
|
||||
}
|
||||
}
|
||||
174
Task/Huffman-coding/C/huffman-coding-1.c
Normal file
174
Task/Huffman-coding/C/huffman-coding-1.c
Normal file
|
|
@ -0,0 +1,174 @@
|
|||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
|
||||
#define BYTES 256
|
||||
|
||||
struct huffcode {
|
||||
int nbits;
|
||||
int code;
|
||||
};
|
||||
typedef struct huffcode huffcode_t;
|
||||
|
||||
struct huffheap {
|
||||
int *h;
|
||||
int n, s, cs;
|
||||
long *f;
|
||||
};
|
||||
typedef struct huffheap heap_t;
|
||||
|
||||
/* heap handling funcs */
|
||||
static heap_t *_heap_create(int s, long *f)
|
||||
{
|
||||
heap_t *h;
|
||||
h = malloc(sizeof(heap_t));
|
||||
h->h = malloc(sizeof(int)*s);
|
||||
h->s = h->cs = s;
|
||||
h->n = 0;
|
||||
h->f = f;
|
||||
return h;
|
||||
}
|
||||
|
||||
static void _heap_destroy(heap_t *heap)
|
||||
{
|
||||
free(heap->h);
|
||||
free(heap);
|
||||
}
|
||||
|
||||
#define swap_(I,J) do { int t_; t_ = a[(I)]; \
|
||||
a[(I)] = a[(J)]; a[(J)] = t_; } while(0)
|
||||
static void _heap_sort(heap_t *heap)
|
||||
{
|
||||
int i=1, j=2; /* gnome sort */
|
||||
int *a = heap->h;
|
||||
|
||||
while(i < heap->n) { /* smaller values are kept at the end */
|
||||
if ( heap->f[a[i-1]] >= heap->f[a[i]] ) {
|
||||
i = j; j++;
|
||||
} else {
|
||||
swap_(i-1, i);
|
||||
i--;
|
||||
i = (i==0) ? j++ : i;
|
||||
}
|
||||
}
|
||||
}
|
||||
#undef swap_
|
||||
|
||||
static void _heap_add(heap_t *heap, int c)
|
||||
{
|
||||
if ( (heap->n + 1) > heap->s ) {
|
||||
heap->h = realloc(heap->h, heap->s + heap->cs);
|
||||
heap->s += heap->cs;
|
||||
}
|
||||
heap->h[heap->n] = c;
|
||||
heap->n++;
|
||||
_heap_sort(heap);
|
||||
}
|
||||
|
||||
static int _heap_remove(heap_t *heap)
|
||||
{
|
||||
if ( heap->n > 0 ) {
|
||||
heap->n--;
|
||||
return heap->h[heap->n];
|
||||
}
|
||||
return -1;
|
||||
}
|
||||
|
||||
/* huffmann code generator */
|
||||
huffcode_t **create_huffman_codes(long *freqs)
|
||||
{
|
||||
huffcode_t **codes;
|
||||
heap_t *heap;
|
||||
long efreqs[BYTES*2];
|
||||
int preds[BYTES*2];
|
||||
int i, extf=BYTES;
|
||||
int r1, r2;
|
||||
|
||||
memcpy(efreqs, freqs, sizeof(long)*BYTES);
|
||||
memset(&efreqs[BYTES], 0, sizeof(long)*BYTES);
|
||||
|
||||
heap = _heap_create(BYTES*2, efreqs);
|
||||
if ( heap == NULL ) return NULL;
|
||||
|
||||
for(i=0; i < BYTES; i++) if ( efreqs[i] > 0 ) _heap_add(heap, i);
|
||||
|
||||
while( heap->n > 1 )
|
||||
{
|
||||
r1 = _heap_remove(heap);
|
||||
r2 = _heap_remove(heap);
|
||||
efreqs[extf] = efreqs[r1] + efreqs[r2];
|
||||
_heap_add(heap, extf);
|
||||
preds[r1] = extf;
|
||||
preds[r2] = -extf;
|
||||
extf++;
|
||||
}
|
||||
r1 = _heap_remove(heap);
|
||||
preds[r1] = r1;
|
||||
_heap_destroy(heap);
|
||||
|
||||
codes = malloc(sizeof(huffcode_t *)*BYTES);
|
||||
|
||||
int bc, bn, ix;
|
||||
for(i=0; i < BYTES; i++) {
|
||||
bc=0; bn=0;
|
||||
if ( efreqs[i] == 0 ) { codes[i] = NULL; continue; }
|
||||
ix = i;
|
||||
while( abs(preds[ix]) != ix ) {
|
||||
bc |= ((preds[ix] >= 0) ? 1 : 0 ) << bn;
|
||||
ix = abs(preds[ix]);
|
||||
bn++;
|
||||
}
|
||||
codes[i] = malloc(sizeof(huffcode_t));
|
||||
codes[i]->nbits = bn;
|
||||
codes[i]->code = bc;
|
||||
}
|
||||
return codes;
|
||||
}
|
||||
|
||||
void free_huffman_codes(huffcode_t **c)
|
||||
{
|
||||
int i;
|
||||
|
||||
for(i=0; i < BYTES; i++) free(c[i]);
|
||||
free(c);
|
||||
}
|
||||
|
||||
#define MAXBITSPERCODE 100
|
||||
|
||||
void inttobits(int c, int n, char *s)
|
||||
{
|
||||
s[n] = 0;
|
||||
while(n > 0) {
|
||||
s[n-1] = (c%2) + '0';
|
||||
c >>= 1; n--;
|
||||
}
|
||||
}
|
||||
|
||||
const char *test = "this is an example for huffman encoding";
|
||||
|
||||
int main()
|
||||
{
|
||||
huffcode_t **r;
|
||||
int i;
|
||||
char strbit[MAXBITSPERCODE];
|
||||
const char *p;
|
||||
long freqs[BYTES];
|
||||
|
||||
memset(freqs, 0, sizeof freqs);
|
||||
|
||||
p = test;
|
||||
while(*p != '\0') freqs[*p++]++;
|
||||
|
||||
r = create_huffman_codes(freqs);
|
||||
|
||||
for(i=0; i < BYTES; i++) {
|
||||
if ( r[i] != NULL ) {
|
||||
inttobits(r[i]->code, r[i]->nbits, strbit);
|
||||
printf("%c (%d) %s\n", i, r[i]->code, strbit);
|
||||
}
|
||||
}
|
||||
|
||||
free_huffman_codes(r);
|
||||
|
||||
return 0;
|
||||
}
|
||||
122
Task/Huffman-coding/C/huffman-coding-2.c
Normal file
122
Task/Huffman-coding/C/huffman-coding-2.c
Normal file
|
|
@ -0,0 +1,122 @@
|
|||
#include <stdio.h>
|
||||
#include <string.h>
|
||||
|
||||
typedef struct node_t {
|
||||
struct node_t *left, *right;
|
||||
int freq;
|
||||
char c;
|
||||
} *node;
|
||||
|
||||
struct node_t pool[256] = {{0}};
|
||||
node qqq[255], *q = qqq - 1;
|
||||
int n_nodes = 0, qend = 1;
|
||||
char *code[128] = {0}, buf[1024];
|
||||
|
||||
node new_node(int freq, char c, node a, node b)
|
||||
{
|
||||
node n = pool + n_nodes++;
|
||||
if (freq) n->c = c, n->freq = freq;
|
||||
else {
|
||||
n->left = a, n->right = b;
|
||||
n->freq = a->freq + b->freq;
|
||||
}
|
||||
return n;
|
||||
}
|
||||
|
||||
/* priority queue */
|
||||
void qinsert(node n)
|
||||
{
|
||||
int j, i = qend++;
|
||||
while ((j = i / 2)) {
|
||||
if (q[j]->freq <= n->freq) break;
|
||||
q[i] = q[j], i = j;
|
||||
}
|
||||
q[i] = n;
|
||||
}
|
||||
|
||||
node qremove()
|
||||
{
|
||||
int i, l;
|
||||
node n = q[i = 1];
|
||||
|
||||
if (qend < 2) return 0;
|
||||
qend--;
|
||||
while ((l = i * 2) < qend) {
|
||||
if (l + 1 < qend && q[l + 1]->freq < q[l]->freq) l++;
|
||||
q[i] = q[l], i = l;
|
||||
}
|
||||
q[i] = q[qend];
|
||||
return n;
|
||||
}
|
||||
|
||||
/* walk the tree and put 0s and 1s */
|
||||
void build_code(node n, char *s, int len)
|
||||
{
|
||||
static char *out = buf;
|
||||
if (n->c) {
|
||||
s[len] = 0;
|
||||
strcpy(out, s);
|
||||
code[n->c] = out;
|
||||
out += len + 1;
|
||||
return;
|
||||
}
|
||||
|
||||
s[len] = '0'; build_code(n->left, s, len + 1);
|
||||
s[len] = '1'; build_code(n->right, s, len + 1);
|
||||
}
|
||||
|
||||
void init(const char *s)
|
||||
{
|
||||
int i, freq[128] = {0};
|
||||
char c[16];
|
||||
|
||||
while (*s) freq[(int)*s++]++;
|
||||
|
||||
for (i = 0; i < 128; i++)
|
||||
if (freq[i]) qinsert(new_node(freq[i], i, 0, 0));
|
||||
|
||||
while (qend > 2)
|
||||
qinsert(new_node(0, 0, qremove(), qremove()));
|
||||
|
||||
build_code(q[1], c, 0);
|
||||
}
|
||||
|
||||
void encode(const char *s, char *out)
|
||||
{
|
||||
while (*s) {
|
||||
strcpy(out, code[*s]);
|
||||
out += strlen(code[*s++]);
|
||||
}
|
||||
}
|
||||
|
||||
void decode(const char *s, node t)
|
||||
{
|
||||
node n = t;
|
||||
while (*s) {
|
||||
if (*s++ == '0') n = n->left;
|
||||
else n = n->right;
|
||||
|
||||
if (n->c) putchar(n->c), n = t;
|
||||
}
|
||||
|
||||
putchar('\n');
|
||||
if (t != n) printf("garbage input\n");
|
||||
}
|
||||
|
||||
int main(void)
|
||||
{
|
||||
int i;
|
||||
const char *str = "this is an example for huffman encoding", buf[1024];
|
||||
|
||||
init(str);
|
||||
for (i = 0; i < 128; i++)
|
||||
if (code[i]) printf("'%c': %s\n", i, code[i]);
|
||||
|
||||
encode(str, buf);
|
||||
printf("encoded: %s\n", buf);
|
||||
|
||||
printf("decoded: ");
|
||||
decode(buf, q[1]);
|
||||
|
||||
return 0;
|
||||
}
|
||||
21
Task/Huffman-coding/C/huffman-coding-3.c
Normal file
21
Task/Huffman-coding/C/huffman-coding-3.c
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
' ': 000
|
||||
'a': 1000
|
||||
'c': 01101
|
||||
'd': 01100
|
||||
'e': 0101
|
||||
'f': 0010
|
||||
'g': 010000
|
||||
'h': 1101
|
||||
'i': 0011
|
||||
'l': 010001
|
||||
'm': 1111
|
||||
'n': 101
|
||||
'o': 1110
|
||||
'p': 10011
|
||||
'r': 10010
|
||||
's': 1100
|
||||
't': 01111
|
||||
'u': 01110
|
||||
'x': 01001
|
||||
encoded: 0111111010011110000000111100000100010100001010100110001111100110100010101000001011101001000011010111000100010111110001010000101101011011110011000011101010000
|
||||
decoded: this is an example for huffman encoding
|
||||
36
Task/Huffman-coding/Clojure/huffman-coding.clj
Normal file
36
Task/Huffman-coding/Clojure/huffman-coding.clj
Normal file
|
|
@ -0,0 +1,36 @@
|
|||
(use 'clojure.contrib.seq-utils)
|
||||
|
||||
(defn probs [items]
|
||||
(let [freqs (frequencies items) sum (reduce + (vals freqs))]
|
||||
(into {} (map (fn [[k v]] [k (/ v sum)]) freqs))))
|
||||
|
||||
(defn init-pq [weighted-items]
|
||||
(let [comp (proxy [java.util.Comparator] []
|
||||
(compare [a b] (compare (:priority a) (:priority b))))
|
||||
pq (java.util.PriorityQueue. (count weighted-items) comp)]
|
||||
(doseq [[item prob] weighted-items] (.add pq { :symbol item, :priority prob }))
|
||||
pq))
|
||||
|
||||
(defn huffman-tree [pq]
|
||||
(while (> (.size pq) 1)
|
||||
(let [a (.poll pq) b (.poll pq) new-node { :priority (+ (:priority a) (:priority b)), :left a, :right b }]
|
||||
(.add pq new-node)))
|
||||
(.poll pq))
|
||||
|
||||
(defn symbol-map
|
||||
([t] (into {} (symbol-map t [])))
|
||||
([{:keys [symbol,left,right] :as t} code]
|
||||
(if symbol [[symbol code]]
|
||||
(concat (symbol-map left (conj code 0))
|
||||
(symbol-map right (conj code 1))))))
|
||||
|
||||
(defn huffman-encode [items]
|
||||
(-> items probs init-pq huffman-tree symbol-map))
|
||||
|
||||
(defn display-huffman-encode [s]
|
||||
(println "SYMBOL\tWEIGHT\tHUFFMAN CODE")
|
||||
(let [probs (probs (seq s))]
|
||||
(doseq [[char code] (huffman-encode (seq s))]
|
||||
(printf "%s:\t\t%s\t\t%s\n" char (probs char) (apply str code)))))
|
||||
|
||||
(display-huffman-encode "this is an example for huffman encoding")
|
||||
85
Task/Huffman-coding/CoffeeScript/huffman-coding-1.coffee
Normal file
85
Task/Huffman-coding/CoffeeScript/huffman-coding-1.coffee
Normal file
|
|
@ -0,0 +1,85 @@
|
|||
huffman_encoding_table = (counts) ->
|
||||
# counts is a hash where keys are characters and
|
||||
# values are frequencies;
|
||||
# return a hash where keys are codes and values
|
||||
# are characters
|
||||
|
||||
build_huffman_tree = ->
|
||||
# returns a Huffman tree. Each node has
|
||||
# cnt: total frequency of all chars in subtree
|
||||
# c: character to be encoded (leafs only)
|
||||
# children: children nodes (branches only)
|
||||
q = min_queue()
|
||||
for c, cnt of counts
|
||||
q.enqueue cnt,
|
||||
cnt: cnt
|
||||
c: c
|
||||
while q.size() >= 2
|
||||
a = q.dequeue()
|
||||
b = q.dequeue()
|
||||
cnt = a.cnt + b.cnt
|
||||
node =
|
||||
cnt: cnt
|
||||
children: [a, b]
|
||||
q.enqueue cnt, node
|
||||
root = q.dequeue()
|
||||
|
||||
root = build_huffman_tree()
|
||||
|
||||
codes = {}
|
||||
encode = (node, code) ->
|
||||
if node.c?
|
||||
codes[code] = node.c
|
||||
else
|
||||
encode node.children[0], code + "0"
|
||||
encode node.children[1], code + "1"
|
||||
|
||||
encode(root, "")
|
||||
codes
|
||||
|
||||
min_queue = ->
|
||||
# This is very non-optimized; you could use a binary heap for better
|
||||
# performance. Items with smaller priority get dequeued first.
|
||||
arr = []
|
||||
enqueue: (priority, data) ->
|
||||
i = 0
|
||||
while i < arr.length
|
||||
if priority < arr[i].priority
|
||||
break
|
||||
i += 1
|
||||
arr.splice i, 0,
|
||||
priority: priority
|
||||
data: data
|
||||
dequeue: ->
|
||||
arr.shift().data
|
||||
size: -> arr.length
|
||||
_internal: ->
|
||||
arr
|
||||
|
||||
freq_count = (s) ->
|
||||
cnts = {}
|
||||
for c in s
|
||||
cnts[c] ?= 0
|
||||
cnts[c] += 1
|
||||
cnts
|
||||
|
||||
rpad = (s, n) ->
|
||||
while s.length < n
|
||||
s += ' '
|
||||
s
|
||||
|
||||
examples = [
|
||||
"this is an example for huffman encoding"
|
||||
"abcd"
|
||||
"abbccccddddddddeeeeeeeee"
|
||||
]
|
||||
|
||||
for s in examples
|
||||
console.log "---- #{s}"
|
||||
counts = freq_count(s)
|
||||
huffman_table = huffman_encoding_table(counts)
|
||||
codes = (code for code of huffman_table).sort()
|
||||
for code in codes
|
||||
c = huffman_table[code]
|
||||
console.log "#{rpad(code, 5)}: #{c} (#{counts[c]})"
|
||||
console.log()
|
||||
34
Task/Huffman-coding/CoffeeScript/huffman-coding-2.coffee
Normal file
34
Task/Huffman-coding/CoffeeScript/huffman-coding-2.coffee
Normal file
|
|
@ -0,0 +1,34 @@
|
|||
> coffee huffman.coffee
|
||||
---- this is an example for huffman encoding
|
||||
000 : n (4)
|
||||
0010 : s (2)
|
||||
0011 : m (2)
|
||||
0100 : o (2)
|
||||
01010: t (1)
|
||||
01011: x (1)
|
||||
01100: p (1)
|
||||
01101: l (1)
|
||||
01110: r (1)
|
||||
01111: u (1)
|
||||
10000: c (1)
|
||||
10001: d (1)
|
||||
1001 : i (3)
|
||||
101 : (6)
|
||||
1100 : a (3)
|
||||
1101 : e (3)
|
||||
1110 : f (3)
|
||||
11110: g (1)
|
||||
11111: h (2)
|
||||
|
||||
---- abcd
|
||||
00 : a (1)
|
||||
01 : b (1)
|
||||
10 : c (1)
|
||||
11 : d (1)
|
||||
|
||||
---- abbccccddddddddeeeeeeeee
|
||||
0 : e (9)
|
||||
1000 : a (1)
|
||||
1001 : b (2)
|
||||
101 : c (4)
|
||||
11 : d (8)
|
||||
59
Task/Huffman-coding/Common-Lisp/huffman-coding.lisp
Normal file
59
Task/Huffman-coding/Common-Lisp/huffman-coding.lisp
Normal file
|
|
@ -0,0 +1,59 @@
|
|||
(defstruct huffman-node
|
||||
(weight 0 :type number)
|
||||
(element nil :type t)
|
||||
(encoding nil :type (or null bit-vector))
|
||||
(left nil :type (or null huffman-node))
|
||||
(right nil :type (or null huffman-node)))
|
||||
|
||||
(defun initial-huffman-nodes (sequence &key (test 'eql))
|
||||
(let* ((length (length sequence))
|
||||
(increment (/ 1 length))
|
||||
(nodes (make-hash-table :size length :test test))
|
||||
(queue '()))
|
||||
(map nil #'(lambda (element)
|
||||
(multiple-value-bind (node presentp) (gethash element nodes)
|
||||
(if presentp
|
||||
(incf (huffman-node-weight node) increment)
|
||||
(let ((node (make-huffman-node :weight increment
|
||||
:element element)))
|
||||
(setf (gethash element nodes) node
|
||||
queue (list* node queue))))))
|
||||
sequence)
|
||||
(values nodes (sort queue '< :key 'huffman-node-weight))))
|
||||
|
||||
(defun huffman-tree (sequence &key (test 'eql))
|
||||
(multiple-value-bind (nodes queue)
|
||||
(initial-huffman-nodes sequence :test test)
|
||||
(do () ((endp (rest queue)) (values nodes (first queue)))
|
||||
(destructuring-bind (n1 n2 &rest queue-rest) queue
|
||||
(let ((n3 (make-huffman-node
|
||||
:left n1
|
||||
:right n2
|
||||
:weight (+ (huffman-node-weight n1)
|
||||
(huffman-node-weight n2)))))
|
||||
(setf queue (merge 'list (list n3) queue-rest '<
|
||||
:key 'huffman-node-weight)))))))1
|
||||
|
||||
(defun huffman-codes (sequence &key (test 'eql))
|
||||
(multiple-value-bind (nodes tree)
|
||||
(huffman-tree sequence :test test)
|
||||
(labels ((hc (node length bits)
|
||||
(let ((left (huffman-node-left node))
|
||||
(right (huffman-node-right node)))
|
||||
(cond
|
||||
((and (null left) (null right))
|
||||
(setf (huffman-node-encoding node)
|
||||
(make-array length :element-type 'bit
|
||||
:initial-contents (reverse bits))))
|
||||
(t (hc left (1+ length) (list* 0 bits))
|
||||
(hc right (1+ length) (list* 1 bits)))))))
|
||||
(hc tree 0 '())
|
||||
nodes)))
|
||||
|
||||
(defun print-huffman-code-table (nodes &optional (out *standard-output*))
|
||||
(format out "~&Element~10tWeight~20tCode")
|
||||
(loop for node being each hash-value of nodes
|
||||
do (format out "~&~s~10t~s~20t~s"
|
||||
(huffman-node-element node)
|
||||
(huffman-node-weight node)
|
||||
(huffman-node-encoding node))))
|
||||
21
Task/Huffman-coding/D/huffman-coding.d
Normal file
21
Task/Huffman-coding/D/huffman-coding.d
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
import std.stdio, std.algorithm, std.typecons, std.container,std.array;
|
||||
|
||||
auto encode(T)(Group!("a == b", T[]) sf) {
|
||||
auto heap = sf.map!(s => tuple(s[1], [tuple(s[0], "")]))
|
||||
.array.heapify!q{b < a};
|
||||
|
||||
while (heap.length > 1) {
|
||||
auto lo = heap.front; heap.removeFront;
|
||||
auto hi = heap.front; heap.removeFront;
|
||||
foreach (ref pair; lo[1]) pair[1] = '0' ~ pair[1];
|
||||
foreach (ref pair; hi[1]) pair[1] = '1' ~ pair[1];
|
||||
heap.insert(tuple(lo[0] + hi[0], lo[1] ~ hi[1]));
|
||||
}
|
||||
return heap.front[1].schwartzSort!q{tuple(a[1].length, a[0])};
|
||||
}
|
||||
|
||||
void main() {
|
||||
auto s = "this is an example for huffman encoding"d;
|
||||
foreach (p; s.dup.sort().release.group.encode)
|
||||
writefln("'%s' %s", p[]);
|
||||
}
|
||||
97
Task/Huffman-coding/Fantom/huffman-coding.fantom
Normal file
97
Task/Huffman-coding/Fantom/huffman-coding.fantom
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
class Node
|
||||
{
|
||||
Float probability := 0.0f
|
||||
}
|
||||
|
||||
class Leaf : Node
|
||||
{
|
||||
Int character
|
||||
|
||||
new make (Int character, Float probability)
|
||||
{
|
||||
this.character = character
|
||||
this.probability = probability
|
||||
}
|
||||
}
|
||||
|
||||
class Branch : Node
|
||||
{
|
||||
Node left
|
||||
Node right
|
||||
|
||||
new make (Node left, Node right)
|
||||
{
|
||||
this.left = left
|
||||
this.right = right
|
||||
probability = this.left.probability + this.right.probability
|
||||
}
|
||||
}
|
||||
|
||||
class Huffman
|
||||
{
|
||||
Node[] queue := [,]
|
||||
Str:Str table := [:]
|
||||
|
||||
new make (Int[] items)
|
||||
{
|
||||
uniqueItems := items.dup.unique
|
||||
uniqueItems.each |Int item|
|
||||
{
|
||||
num := items.findAll { it == item }.size
|
||||
queue.add (Leaf(item, num.toFloat / items.size))
|
||||
}
|
||||
createTree
|
||||
createTable
|
||||
}
|
||||
|
||||
Void createTree ()
|
||||
{
|
||||
while (queue.size > 1)
|
||||
{
|
||||
queue.sort |a,b| {a.probability <=> b.probability}
|
||||
node1 := queue.removeAt (0)
|
||||
node2 := queue.removeAt (0)
|
||||
queue.add (Branch (node1, node2))
|
||||
}
|
||||
}
|
||||
|
||||
Void traverse (Node node, Str encoding)
|
||||
{
|
||||
if (node is Leaf)
|
||||
{
|
||||
table[(node as Leaf).character.toChar] = encoding
|
||||
}
|
||||
else // (node is Branch)
|
||||
{
|
||||
traverse ((node as Branch).left, encoding + "0")
|
||||
traverse ((node as Branch).right, encoding + "1")
|
||||
}
|
||||
}
|
||||
|
||||
Void createTable ()
|
||||
{
|
||||
if (queue.size != 1) return // error!
|
||||
traverse (queue.first, "")
|
||||
}
|
||||
|
||||
override Str toStr ()
|
||||
{
|
||||
result := "Huffman Encoding Table:\n"
|
||||
table.keys.sort.each |Str key|
|
||||
{
|
||||
result += "$key -> ${table[key]}\n"
|
||||
}
|
||||
return result
|
||||
}
|
||||
}
|
||||
|
||||
class Main
|
||||
{
|
||||
public static Void main ()
|
||||
{
|
||||
example := "this is an example for huffman encoding"
|
||||
huffman := Huffman (example.chars)
|
||||
echo ("From \"$example\"")
|
||||
echo (huffman)
|
||||
}
|
||||
}
|
||||
97
Task/Huffman-coding/Go/huffman-coding-1.go
Normal file
97
Task/Huffman-coding/Go/huffman-coding-1.go
Normal file
|
|
@ -0,0 +1,97 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"container/heap"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type HuffmanTree interface {
|
||||
Freq() int
|
||||
}
|
||||
|
||||
type HuffmanLeaf struct {
|
||||
freq int
|
||||
value rune
|
||||
}
|
||||
|
||||
type HuffmanNode struct {
|
||||
freq int
|
||||
left, right HuffmanTree
|
||||
}
|
||||
|
||||
func (self HuffmanLeaf) Freq() int {
|
||||
return self.freq
|
||||
}
|
||||
|
||||
func (self HuffmanNode) Freq() int {
|
||||
return self.freq
|
||||
}
|
||||
|
||||
type treeHeap []HuffmanTree
|
||||
|
||||
func (th treeHeap) Len() int { return len(th) }
|
||||
func (th treeHeap) Less(i, j int) bool {
|
||||
return th[i].Freq() < th[j].Freq()
|
||||
}
|
||||
func (th *treeHeap) Push(ele interface{}) {
|
||||
*th = append(*th, ele.(HuffmanTree))
|
||||
}
|
||||
func (th *treeHeap) Pop() (popped interface{}) {
|
||||
popped = (*th)[len(*th)-1]
|
||||
*th = (*th)[:len(*th)-1]
|
||||
return
|
||||
}
|
||||
func (th treeHeap) Swap(i, j int) { th[i], th[j] = th[j], th[i] }
|
||||
|
||||
func buildTree(symFreqs map[rune]int) HuffmanTree {
|
||||
var trees treeHeap
|
||||
for c, f := range symFreqs {
|
||||
trees = append(trees, HuffmanLeaf{f, c})
|
||||
}
|
||||
heap.Init(&trees)
|
||||
for trees.Len() > 1 {
|
||||
// two trees with least frequency
|
||||
a := heap.Pop(&trees).(HuffmanTree)
|
||||
b := heap.Pop(&trees).(HuffmanTree)
|
||||
|
||||
// put into new node and re-insert into queue
|
||||
heap.Push(&trees, HuffmanNode{a.Freq() + b.Freq(), a, b})
|
||||
}
|
||||
return heap.Pop(&trees).(HuffmanTree)
|
||||
}
|
||||
|
||||
func printCodes(tree HuffmanTree, prefix []byte) {
|
||||
switch i := tree.(type) {
|
||||
case HuffmanLeaf:
|
||||
// print out symbol, frequency, and code for this
|
||||
// leaf (which is just the prefix)
|
||||
fmt.Printf("%c\t%d\t%s\n", i.value, i.freq, string(prefix))
|
||||
case HuffmanNode:
|
||||
// traverse left
|
||||
prefix = append(prefix, '0')
|
||||
printCodes(i.left, prefix)
|
||||
prefix = prefix[:len(prefix)-1]
|
||||
|
||||
// traverse right
|
||||
prefix = append(prefix, '1')
|
||||
printCodes(i.right, prefix)
|
||||
prefix = prefix[:len(prefix)-1]
|
||||
}
|
||||
}
|
||||
|
||||
func main() {
|
||||
test := "this is an example for huffman encoding"
|
||||
|
||||
symFreqs := make(map[rune]int)
|
||||
// read each symbol and record the frequencies
|
||||
for _, c := range test {
|
||||
symFreqs[c]++
|
||||
}
|
||||
|
||||
// build tree
|
||||
tree := buildTree(symFreqs)
|
||||
|
||||
// print out results
|
||||
fmt.Println("SYMBOL\tWEIGHT\tHUFFMAN CODE")
|
||||
printCodes(tree, []byte{})
|
||||
}
|
||||
65
Task/Huffman-coding/Go/huffman-coding-2.go
Normal file
65
Task/Huffman-coding/Go/huffman-coding-2.go
Normal file
|
|
@ -0,0 +1,65 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"container/heap"
|
||||
"fmt"
|
||||
)
|
||||
|
||||
type coded struct {
|
||||
sym rune
|
||||
code string
|
||||
}
|
||||
|
||||
type counted struct {
|
||||
total int
|
||||
syms []coded
|
||||
}
|
||||
|
||||
type cHeap []counted
|
||||
|
||||
// satisfy heap.Interface
|
||||
func (c cHeap) Len() int { return len(c) }
|
||||
func (c cHeap) Less(i, j int) bool { return c[i].total < c[j].total }
|
||||
func (c cHeap) Swap(i, j int) { c[i], c[j] = c[j], c[i] }
|
||||
func (c *cHeap) Push(ele interface{}) {
|
||||
*c = append(*c, ele.(counted))
|
||||
}
|
||||
func (c *cHeap) Pop() (popped interface{}) {
|
||||
popped = (*c)[len(*c)-1]
|
||||
*c = (*c)[:len(*c)-1]
|
||||
return
|
||||
}
|
||||
|
||||
func encode(sym2freq map[rune]int) []coded {
|
||||
var ch cHeap
|
||||
for sym, freq := range sym2freq {
|
||||
ch = append(ch, counted{freq, []coded{{sym: sym}}})
|
||||
}
|
||||
heap.Init(&ch)
|
||||
for len(ch) > 1 {
|
||||
a := heap.Pop(&ch).(counted)
|
||||
b := heap.Pop(&ch).(counted)
|
||||
for i, c := range a.syms {
|
||||
a.syms[i].code = "0" + c.code
|
||||
}
|
||||
for i, c := range b.syms {
|
||||
b.syms[i].code = "1" + c.code
|
||||
}
|
||||
heap.Push(&ch, counted{a.total + b.total, append(a.syms, b.syms...)})
|
||||
}
|
||||
return heap.Pop(&ch).(counted).syms
|
||||
}
|
||||
|
||||
const txt = "this is an example for huffman encoding"
|
||||
|
||||
func main() {
|
||||
sym2freq := make(map[rune]int)
|
||||
for _, c := range txt {
|
||||
sym2freq[c]++
|
||||
}
|
||||
table := encode(sym2freq)
|
||||
fmt.Println("Symbol Weight Huffman Code")
|
||||
for _, c := range table {
|
||||
fmt.Printf(" %c %d %s\n", c.sym, sym2freq[c.sym], c.code)
|
||||
}
|
||||
}
|
||||
24
Task/Huffman-coding/Haskell/huffman-coding-1.hs
Normal file
24
Task/Huffman-coding/Haskell/huffman-coding-1.hs
Normal file
|
|
@ -0,0 +1,24 @@
|
|||
import Data.List
|
||||
import Control.Arrow
|
||||
import Data.Ord
|
||||
|
||||
data HTree a = Leaf a | Branch (HTree a) (HTree a)
|
||||
deriving (Show, Eq, Ord)
|
||||
|
||||
test :: String -> IO ()
|
||||
test s = mapM_ (\(a,b)-> putStrLn ('\'' : a : "\' : " ++ b))
|
||||
. serialize . huffmanTree . freq $ s
|
||||
|
||||
serialize :: HTree a -> [(a, String)]
|
||||
serialize (Branch l r) = map (second('0':)) (serialize l) ++ map (second('1':)) (serialize r)
|
||||
serialize (Leaf x) = [(x, "")]
|
||||
|
||||
huffmanTree :: (Ord w, Num w) => [(w, a)] -> HTree a
|
||||
huffmanTree = snd . head . until (null.tail) hstep
|
||||
. sortBy (comparing fst) . map (second Leaf)
|
||||
|
||||
hstep :: (Ord a, Num a) => [(a, HTree b)] -> [(a, HTree b)]
|
||||
hstep ((w1,t1):(w2,t2):wts) = insertBy (comparing fst) (w1 + w2, Branch t1 t2) wts
|
||||
|
||||
freq :: Ord a => [a] -> [(Int, a)]
|
||||
freq = map (length &&& head) . group . sort
|
||||
20
Task/Huffman-coding/Haskell/huffman-coding-2.hs
Normal file
20
Task/Huffman-coding/Haskell/huffman-coding-2.hs
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
*Main> test "this is an example for huffman encoding"
|
||||
'p' : 00000
|
||||
'r' : 00001
|
||||
'g' : 00010
|
||||
'l' : 00011
|
||||
'n' : 001
|
||||
'm' : 0100
|
||||
'o' : 0101
|
||||
'c' : 01100
|
||||
'd' : 01101
|
||||
'h' : 0111
|
||||
's' : 1000
|
||||
'x' : 10010
|
||||
't' : 100110
|
||||
'u' : 100111
|
||||
'f' : 1010
|
||||
'i' : 1011
|
||||
'a' : 1100
|
||||
'e' : 1101
|
||||
' ' : 111
|
||||
12
Task/Huffman-coding/Haskell/huffman-coding-3.hs
Normal file
12
Task/Huffman-coding/Haskell/huffman-coding-3.hs
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import qualified Data.Set as S
|
||||
|
||||
htree :: (Ord t, Num t, Ord a) => S.Set (t, HTree a) -> HTree a
|
||||
htree ts | S.null ts_1 = t1
|
||||
| otherwise = htree ts_3
|
||||
where
|
||||
((w1,t1), ts_1) = S.deleteFindMin ts
|
||||
((w2,t2), ts_2) = S.deleteFindMin ts_1
|
||||
ts_3 = S.insert (w1 + w2, Branch t1 t2) ts_2
|
||||
|
||||
huffmanTree :: (Ord w, Num w, Ord a) => [(w, a)] -> HTree a
|
||||
huffmanTree = htree . S.fromList . map (second Leaf)
|
||||
17
Task/Huffman-coding/Haskell/huffman-coding-4.hs
Normal file
17
Task/Huffman-coding/Haskell/huffman-coding-4.hs
Normal file
|
|
@ -0,0 +1,17 @@
|
|||
import Data.List (sortBy, insertBy, sort, group)
|
||||
import Control.Arrow (second, (&&&))
|
||||
import Data.Ord (comparing)
|
||||
|
||||
freq :: Ord a => [a] -> [(Int, a)]
|
||||
freq = map (length &&& head) . group . sort
|
||||
|
||||
huffman :: [(Int, Char)] -> [(Char, String)]
|
||||
huffman = reduce . map (\(p, c) -> (p, [(c ,"")])) . sortBy (comparing fst)
|
||||
where add (p1, xs1) (p2, xs2) = (p1 + p2, map (second ('0':)) xs1 ++ map (second ('1':)) xs2)
|
||||
reduce [(_, ys)] = sortBy (comparing fst) ys
|
||||
reduce (x1:x2:xs) = reduce $ insertBy (comparing fst) (add x1 x2) xs
|
||||
|
||||
test s = mapM_ (\(a, b) -> putStrLn ('\'' : a : "\' : " ++ b)) . huffman . freq $ s
|
||||
|
||||
main = do
|
||||
test "this is an example for huffman encoding"
|
||||
60
Task/Huffman-coding/Icon/huffman-coding-1.icon
Normal file
60
Task/Huffman-coding/Icon/huffman-coding-1.icon
Normal file
|
|
@ -0,0 +1,60 @@
|
|||
record huffnode(l,r,n,c) # internal and leaf nodes
|
||||
record huffcode(c,n,b,i) # encoding table char, freq, bitstring, bits (int)
|
||||
|
||||
procedure main()
|
||||
|
||||
s := "this is an example for huffman encoding"
|
||||
|
||||
Count := huffcount(s) # frequency count
|
||||
Tree := huffTree(Count) # heap and tree
|
||||
|
||||
Code := [] # extract encodings
|
||||
CodeT := table()
|
||||
every x := huffBits(Tree) do
|
||||
put( Code, CodeT[c] := huffcode( c := x[-1], Count[c].n, b := x[1:-1], integer("2r"||b) ) )
|
||||
|
||||
|
||||
Code := sortf( Code, 1 ) # show table in char order
|
||||
write("Input String : ",image(s))
|
||||
write(right("char",5), right("freq",5), " encoding" )
|
||||
every write(right(image((x := !Code).c),5), right(x.n,5), " ", x.b )
|
||||
|
||||
end
|
||||
|
||||
procedure huffBits(N) # generates huffman bitcodes with trailing character
|
||||
if \N.c then return N.c # . append leaf char code
|
||||
suspend "0" || huffBits(N.l) # . left
|
||||
suspend "1" || huffBits(N.r) # . right
|
||||
end
|
||||
|
||||
|
||||
procedure huffTree(T) # two queue huffman tree method
|
||||
local Q1,Q2,x,n1,n2
|
||||
|
||||
Q1 := [] # queue of characters and weights
|
||||
every x := !T do # ensure all are huffnodes
|
||||
if type(x) == "huffnode" then put(Q1,x) else runerr(205,x)
|
||||
Q1 := sortf(Q1,3) # sort by weight ( 3 means by .n )
|
||||
|
||||
if *Q1 > 1 then Q2 := []
|
||||
while *Q1+*\Q2 > 1 do { # While there is more than one node ...
|
||||
|
||||
n1 := if Q1[1] & ( ( Q1[1].n <= Q2[1].n ) | not Q2[1] ) then get(Q1) else get(Q2) # lowest weight from Q1 or Q2
|
||||
n2 := if Q1[1] & ( ( Q1[1].n <= Q2[1].n ) | not Q2[1] ) then get(Q1) else get(Q2) # lowest weight from Q1 or Q2
|
||||
|
||||
put( Q2, huffnode( n1, n2, n1.n + n2.n ) ) # new weighted node to end of Q2
|
||||
}
|
||||
|
||||
return (\Q2 | Q1)[1] # return the root node
|
||||
end
|
||||
|
||||
procedure huffcount(s) # return characters and frequencies in a table of huffnodes by char
|
||||
local c,T
|
||||
|
||||
T := table()
|
||||
every c := !s do {
|
||||
/T[c] := huffnode(,,0,c)
|
||||
T[c].n +:= 1
|
||||
}
|
||||
return T
|
||||
end
|
||||
30
Task/Huffman-coding/Icon/huffman-coding-2.icon
Normal file
30
Task/Huffman-coding/Icon/huffman-coding-2.icon
Normal file
|
|
@ -0,0 +1,30 @@
|
|||
import Collections
|
||||
|
||||
procedure main(A)
|
||||
every line := !&input do {
|
||||
every (t := table(0))[!line] +:= 1 # Frequency table
|
||||
heap := Heap(sort(t), field, "<") # Initial priority queue
|
||||
while heap.size() > 1 do { # Tree construction
|
||||
every (p1|p2) := heap.get()
|
||||
heap.add([&null, p1[2]+p2[2], p1, p2])
|
||||
}
|
||||
codes := treeWalk(heap.get(),"") # Get codes from tree
|
||||
write("Huffman encoding:") # Display codes
|
||||
every pair := !sort(codes) do
|
||||
write("\t'",\pair[1],"'-> ",pair[2])
|
||||
}
|
||||
end
|
||||
|
||||
procedure field(node) # selector function for Heap
|
||||
return node[2] # field to use for priority ordering
|
||||
end
|
||||
|
||||
procedure treeWalk(node, prefix, codeMap)
|
||||
/codeMap := table("")
|
||||
if /node[1] then { # interior node
|
||||
treeWalk(node[3], prefix||"0", codeMap)
|
||||
treeWalk(node[4], prefix||"1", codeMap)
|
||||
}
|
||||
else codeMap[node[1]] := prefix
|
||||
return codeMap
|
||||
end
|
||||
14
Task/Huffman-coding/J/huffman-coding-1.j
Normal file
14
Task/Huffman-coding/J/huffman-coding-1.j
Normal file
|
|
@ -0,0 +1,14 @@
|
|||
hc=: 4 : 0
|
||||
if. 1=#x do. y
|
||||
else. ((i{x),+/j{x) hc (i{y),<j{y [ i=. (i.#x) -. j=. 2{./:x end.
|
||||
)
|
||||
|
||||
hcodes=: 4 : 0
|
||||
assert. x -:&$ y NB. weights and words have same shape
|
||||
assert. (0<:x) *. 1=#$x NB. weights are non-negative
|
||||
assert. 1 >: L.y NB. words are boxed not more than once
|
||||
w=. ,&.> y NB. standardized words
|
||||
assert. w -: ~.w NB. words are unique
|
||||
t=. 0 {:: x hc w NB. minimal weight binary tree
|
||||
((< S: 0 t) i. w) { <@(1&=)@; S: 1 {:: t
|
||||
)
|
||||
20
Task/Huffman-coding/J/huffman-coding-2.j
Normal file
20
Task/Huffman-coding/J/huffman-coding-2.j
Normal file
|
|
@ -0,0 +1,20 @@
|
|||
;"1":L:0(#/.~ (],.(<' '),.hcodes) ,&.>@~.)'this is an example for huffman encoding'
|
||||
t 0 1 0 1 0
|
||||
h 1 1 1 1 1
|
||||
i 1 0 0 1
|
||||
s 0 0 1 0
|
||||
1 0 1
|
||||
a 1 1 0 0
|
||||
n 0 0 0
|
||||
e 1 1 0 1
|
||||
x 0 1 0 1 1
|
||||
m 0 0 1 1
|
||||
p 0 1 1 0 0
|
||||
l 0 1 1 0 1
|
||||
f 1 1 1 0
|
||||
o 0 1 0 0
|
||||
r 0 1 1 1 0
|
||||
u 0 1 1 1 1
|
||||
c 1 0 0 0 0
|
||||
d 1 0 0 0 1
|
||||
g 1 1 1 1 0
|
||||
95
Task/Huffman-coding/Java/huffman-coding.java
Normal file
95
Task/Huffman-coding/Java/huffman-coding.java
Normal file
|
|
@ -0,0 +1,95 @@
|
|||
import java.util.*;
|
||||
|
||||
abstract class HuffmanTree implements Comparable<HuffmanTree> {
|
||||
public final int frequency; // the frequency of this tree
|
||||
public HuffmanTree(int freq) { frequency = freq; }
|
||||
|
||||
// compares on the frequency
|
||||
public int compareTo(HuffmanTree tree) {
|
||||
return frequency - tree.frequency;
|
||||
}
|
||||
}
|
||||
|
||||
class HuffmanLeaf extends HuffmanTree {
|
||||
public final char value; // the character this leaf represents
|
||||
|
||||
public HuffmanLeaf(int freq, char val) {
|
||||
super(freq);
|
||||
value = val;
|
||||
}
|
||||
}
|
||||
|
||||
class HuffmanNode extends HuffmanTree {
|
||||
public final HuffmanTree left, right; // subtrees
|
||||
|
||||
public HuffmanNode(HuffmanTree l, HuffmanTree r) {
|
||||
super(l.frequency + r.frequency);
|
||||
left = l;
|
||||
right = r;
|
||||
}
|
||||
}
|
||||
|
||||
public class HuffmanCode {
|
||||
// input is an array of frequencies, indexed by character code
|
||||
public static HuffmanTree buildTree(int[] charFreqs) {
|
||||
PriorityQueue<HuffmanTree> trees = new PriorityQueue<HuffmanTree>();
|
||||
// initially, we have a forest of leaves
|
||||
// one for each non-empty character
|
||||
for (int i = 0; i < charFreqs.length; i++)
|
||||
if (charFreqs[i] > 0)
|
||||
trees.offer(new HuffmanLeaf(charFreqs[i], (char)i));
|
||||
|
||||
assert trees.size() > 0;
|
||||
// loop until there is only one tree left
|
||||
while (trees.size() > 1) {
|
||||
// two trees with least frequency
|
||||
HuffmanTree a = trees.poll();
|
||||
HuffmanTree b = trees.poll();
|
||||
|
||||
// put into new node and re-insert into queue
|
||||
trees.offer(new HuffmanNode(a, b));
|
||||
}
|
||||
return trees.poll();
|
||||
}
|
||||
|
||||
public static void printCodes(HuffmanTree tree, StringBuffer prefix) {
|
||||
assert tree != null;
|
||||
if (tree instanceof HuffmanLeaf) {
|
||||
HuffmanLeaf leaf = (HuffmanLeaf)tree;
|
||||
|
||||
// print out character, frequency, and code for this leaf (which is just the prefix)
|
||||
System.out.println(leaf.value + "\t" + leaf.frequency + "\t" + prefix);
|
||||
|
||||
} else if (tree instanceof HuffmanNode) {
|
||||
HuffmanNode node = (HuffmanNode)tree;
|
||||
|
||||
// traverse left
|
||||
prefix.append('0');
|
||||
printCodes(node.left, prefix);
|
||||
prefix.deleteCharAt(prefix.length()-1);
|
||||
|
||||
// traverse right
|
||||
prefix.append('1');
|
||||
printCodes(node.right, prefix);
|
||||
prefix.deleteCharAt(prefix.length()-1);
|
||||
}
|
||||
}
|
||||
|
||||
public static void main(String[] args) {
|
||||
String test = "this is an example for huffman encoding";
|
||||
|
||||
// we will assume that all our characters will have
|
||||
// code less than 256, for simplicity
|
||||
int[] charFreqs = new int[256];
|
||||
// read each character and record the frequencies
|
||||
for (char c : test.toCharArray())
|
||||
charFreqs[c]++;
|
||||
|
||||
// build tree
|
||||
HuffmanTree tree = buildTree(charFreqs);
|
||||
|
||||
// print out results
|
||||
System.out.println("SYMBOL\tWEIGHT\tHUFFMAN CODE");
|
||||
printCodes(tree, new StringBuffer());
|
||||
}
|
||||
}
|
||||
63
Task/Huffman-coding/JavaScript/huffman-coding-1.js
Normal file
63
Task/Huffman-coding/JavaScript/huffman-coding-1.js
Normal file
|
|
@ -0,0 +1,63 @@
|
|||
function HuffmanEncoding(str) {
|
||||
this.str = str;
|
||||
|
||||
var count_chars = {};
|
||||
for (var i = 0; i < str.length; i++)
|
||||
if (str[i] in count_chars)
|
||||
count_chars[str[i]] ++;
|
||||
else
|
||||
count_chars[str[i]] = 1;
|
||||
|
||||
var pq = new BinaryHeap(function(x){return x[0];});
|
||||
for (var ch in count_chars)
|
||||
pq.push([count_chars[ch], ch]);
|
||||
|
||||
while (pq.size() > 1) {
|
||||
var pair1 = pq.pop();
|
||||
var pair2 = pq.pop();
|
||||
pq.push([pair1[0]+pair2[0], [pair1[1], pair2[1]]]);
|
||||
}
|
||||
|
||||
var tree = pq.pop();
|
||||
this.encoding = {};
|
||||
this._generate_encoding(tree[1], "");
|
||||
|
||||
this.encoded_string = ""
|
||||
for (var i = 0; i < this.str.length; i++) {
|
||||
this.encoded_string += this.encoding[str[i]];
|
||||
}
|
||||
}
|
||||
|
||||
HuffmanEncoding.prototype._generate_encoding = function(ary, prefix) {
|
||||
if (ary instanceof Array) {
|
||||
this._generate_encoding(ary[0], prefix + "0");
|
||||
this._generate_encoding(ary[1], prefix + "1");
|
||||
}
|
||||
else {
|
||||
this.encoding[ary] = prefix;
|
||||
}
|
||||
}
|
||||
|
||||
HuffmanEncoding.prototype.inspect_encoding = function() {
|
||||
for (var ch in this.encoding) {
|
||||
print("'" + ch + "': " + this.encoding[ch])
|
||||
}
|
||||
}
|
||||
|
||||
HuffmanEncoding.prototype.decode = function(encoded) {
|
||||
var rev_enc = {};
|
||||
for (var ch in this.encoding)
|
||||
rev_enc[this.encoding[ch]] = ch;
|
||||
|
||||
var decoded = "";
|
||||
var pos = 0;
|
||||
while (pos < encoded.length) {
|
||||
var key = ""
|
||||
while (!(key in rev_enc)) {
|
||||
key += encoded[pos];
|
||||
pos++;
|
||||
}
|
||||
decoded += rev_enc[key];
|
||||
}
|
||||
return decoded;
|
||||
}
|
||||
13
Task/Huffman-coding/JavaScript/huffman-coding-2.js
Normal file
13
Task/Huffman-coding/JavaScript/huffman-coding-2.js
Normal file
|
|
@ -0,0 +1,13 @@
|
|||
var s = "this is an example for huffman encoding";
|
||||
print(s);
|
||||
|
||||
var huff = new HuffmanEncoding(s);
|
||||
huff.inspect_encoding();
|
||||
|
||||
var e = huff.encoded_string;
|
||||
print(e);
|
||||
|
||||
var t = huff.decode(e);
|
||||
print(t);
|
||||
|
||||
print("is decoded string same as original? " + (s==t));
|
||||
28
Task/Huffman-coding/PHP/huffman-coding.php
Normal file
28
Task/Huffman-coding/PHP/huffman-coding.php
Normal file
|
|
@ -0,0 +1,28 @@
|
|||
<?php
|
||||
function encode($symb2freq) {
|
||||
$heap = new SplPriorityQueue;
|
||||
$heap->setExtractFlags(SplPriorityQueue::EXTR_BOTH);
|
||||
foreach ($symb2freq as $sym => $wt)
|
||||
$heap->insert(array($sym => ''), -$wt);
|
||||
|
||||
while ($heap->count() > 1) {
|
||||
$lo = $heap->extract();
|
||||
$hi = $heap->extract();
|
||||
foreach ($lo['data'] as &$x)
|
||||
$x = '0'.$x;
|
||||
foreach ($hi['data'] as &$x)
|
||||
$x = '1'.$x;
|
||||
$heap->insert($lo['data'] + $hi['data'],
|
||||
$lo['priority'] + $hi['priority']);
|
||||
}
|
||||
$result = $heap->extract();
|
||||
return $result['data'];
|
||||
}
|
||||
|
||||
$txt = 'this is an example for huffman encoding';
|
||||
$symb2freq = array_count_values(str_split($txt));
|
||||
$huff = encode($symb2freq);
|
||||
echo "Symbol\tWeight\tHuffman Code\n";
|
||||
foreach ($huff as $sym => $code)
|
||||
echo "$sym\t$symb2freq[$sym]\t$code\n";
|
||||
?>
|
||||
52
Task/Huffman-coding/Perl/huffman-coding-1.pl
Normal file
52
Task/Huffman-coding/Perl/huffman-coding-1.pl
Normal file
|
|
@ -0,0 +1,52 @@
|
|||
sub make_tree {
|
||||
my %letters;
|
||||
$letters{$_}++ for (split "", shift);
|
||||
my (@nodes, $n) = map({ a=>$_, freq=>$letters{$_} }, keys %letters);
|
||||
while ((@nodes = sort { $a->{freq} <=> $b->{freq}
|
||||
or $a->{a} cmp $b->{a} } @nodes) > 1)
|
||||
{
|
||||
$n = { "0"=>shift(@nodes), "1"=>shift(@nodes) };
|
||||
$n->{freq} = $n->{0}{freq} + $n->{1}{freq};
|
||||
push @nodes, $n;
|
||||
}
|
||||
|
||||
walk($n, "", $n->{tree} = {});
|
||||
$n;
|
||||
}
|
||||
|
||||
sub walk {
|
||||
my ($n, $s, $h) = @_;
|
||||
exists $n->{a} and do {
|
||||
print "'$n->{a}': $s\n";
|
||||
$h->{$n->{a}} = $s if $h;
|
||||
return;
|
||||
};
|
||||
walk($n->{0}, $s.0, $h);
|
||||
walk($n->{1}, $s.1, $h);
|
||||
}
|
||||
|
||||
sub encode {
|
||||
my ($s, $t) = @_;
|
||||
$t = $t->{tree};
|
||||
join("", map($t->{$_}, split("", $s)));
|
||||
}
|
||||
|
||||
sub decode {
|
||||
my @b = split("", shift);
|
||||
my ($n, $out) = $_[0];
|
||||
|
||||
while (@b) {
|
||||
$n = $n->{shift @b};
|
||||
if ($n->{a}) {
|
||||
$out .= $n->{a};
|
||||
$n = $_[0];
|
||||
}
|
||||
}
|
||||
$out;
|
||||
}
|
||||
|
||||
my $text = "this is an example for huffman encoding";
|
||||
my $tree = make_tree($text);
|
||||
my $e = encode($text, $tree);
|
||||
print "$e\n";
|
||||
print decode($e, $tree), "\n";
|
||||
21
Task/Huffman-coding/Perl/huffman-coding-2.pl
Normal file
21
Task/Huffman-coding/Perl/huffman-coding-2.pl
Normal file
|
|
@ -0,0 +1,21 @@
|
|||
'g': 00000
|
||||
'l': 00001
|
||||
'p': 00010
|
||||
'r': 00011
|
||||
't': 00100
|
||||
'u': 00101
|
||||
'h': 0011
|
||||
'm': 0100
|
||||
'o': 0101
|
||||
'n': 011
|
||||
's': 1000
|
||||
'x': 10010
|
||||
'c': 100110
|
||||
'd': 100111
|
||||
'a': 1010
|
||||
'e': 1011
|
||||
'f': 1100
|
||||
'i': 1101
|
||||
' ': 111
|
||||
0010000111101100011111...111110101100000
|
||||
this is an example for huffman encoding
|
||||
18
Task/Huffman-coding/PicoLisp/huffman-coding.l
Normal file
18
Task/Huffman-coding/PicoLisp/huffman-coding.l
Normal file
|
|
@ -0,0 +1,18 @@
|
|||
(de prio (Idx)
|
||||
(while (cadr Idx) (setq Idx @))
|
||||
(car Idx) )
|
||||
|
||||
(let (A NIL P NIL L NIL)
|
||||
(for C (chop "this is an example for huffman encoding")
|
||||
(accu 'A C 1) ) # Count characters
|
||||
(for X A # Build index tree as priority queue
|
||||
(idx 'P (cons (cdr X) (car X)) T) )
|
||||
(while (or (cadr P) (cddr P)) # Remove entries, insert as nodes
|
||||
(let (A (car (idx 'P (prio P) NIL)) B (car (idx 'P (prio P) NIL)))
|
||||
(idx 'P (cons (+ (car A) (car B)) A B) T) ) )
|
||||
(setq P (car P))
|
||||
(recur (P L) # Traverse and print
|
||||
(if (atom (cdr P))
|
||||
(prinl (cdr P) " " L)
|
||||
(recurse (cadr P) (cons 0 L))
|
||||
(recurse (cddr P) (cons 1 L)) ) ) )
|
||||
47
Task/Huffman-coding/Prolog/huffman-coding.pro
Normal file
47
Task/Huffman-coding/Prolog/huffman-coding.pro
Normal file
|
|
@ -0,0 +1,47 @@
|
|||
huffman :-
|
||||
L = 'this is an example for huffman encoding',
|
||||
atom_chars(L, LA),
|
||||
msort(LA, LS),
|
||||
packList(LS, PL),
|
||||
sort(PL, PLS),
|
||||
build_tree(PLS, A),
|
||||
coding(A, [], C),
|
||||
sort(C, SC),
|
||||
format('Symbol~t Weight~t~30|Code~n'),
|
||||
maplist(print_code, SC).
|
||||
|
||||
build_tree([[V1|R1], [V2|R2]|T], AF) :-
|
||||
V is V1 + V2,
|
||||
A = [V, [V1|R1], [V2|R2]],
|
||||
( T=[] -> AF=A ; sort([A|T], NT), build_tree(NT, AF) ).
|
||||
|
||||
coding([_A,FG,FD], Code, CF) :-
|
||||
( is_node(FG) -> coding(FG, [0 | Code], C1)
|
||||
; leaf_coding(FG, [0 | Code], C1) ),
|
||||
( is_node(FD) -> coding(FD, [1 | Code], C2)
|
||||
; leaf_coding(FD, [1 | Code], C2) ),
|
||||
append(C1, C2, CF).
|
||||
|
||||
leaf_coding([FG,FD], Code, CF) :-
|
||||
reverse(Code, CodeR),
|
||||
CF = [[FG, FD, CodeR]] .
|
||||
|
||||
is_node([_V, _FG, _FD]).
|
||||
|
||||
print_code([N, Car, Code]):-
|
||||
format('~w :~t~w~t~30|', [Car, N]),
|
||||
forall(member(V, Code), write(V)),
|
||||
nl.
|
||||
|
||||
packList([], []).
|
||||
packList([X], [[1,X]]) :- !.
|
||||
packList([X|Rest], [XRun|Packed]):-
|
||||
run(X, Rest, XRun, RRest),
|
||||
packList(RRest, Packed).
|
||||
|
||||
run(V, [], [1,V], []).
|
||||
run(V, [V|LRest], [N1,V], RRest):-
|
||||
run(V, LRest, [N, V], RRest),
|
||||
N1 is N + 1.
|
||||
run(V, [Other|RRest], [1,V], [Other|RRest]):-
|
||||
dif(V, Other).
|
||||
27
Task/Huffman-coding/Python/huffman-coding.py
Normal file
27
Task/Huffman-coding/Python/huffman-coding.py
Normal file
|
|
@ -0,0 +1,27 @@
|
|||
from heapq import heappush, heappop, heapify
|
||||
from collections import defaultdict
|
||||
|
||||
def encode(symb2freq):
|
||||
"""Huffman encode the given dict mapping symbols to weights"""
|
||||
heap = [[wt, [sym, ""]] for sym, wt in symb2freq.items()]
|
||||
heapify(heap)
|
||||
while len(heap) > 1:
|
||||
lo = heappop(heap)
|
||||
hi = heappop(heap)
|
||||
for pair in lo[1:]:
|
||||
pair[1] = '0' + pair[1]
|
||||
for pair in hi[1:]:
|
||||
pair[1] = '1' + pair[1]
|
||||
heappush(heap, [lo[0] + hi[0]] + lo[1:] + hi[1:])
|
||||
return sorted(heappop(heap)[1:], key=lambda p: (len(p[-1]), p))
|
||||
|
||||
txt = "this is an example for huffman encoding"
|
||||
symb2freq = defaultdict(int)
|
||||
for ch in txt:
|
||||
symb2freq[ch] += 1
|
||||
# in Python 3.1+:
|
||||
# symb2freq = collections.Counter(txt)
|
||||
huff = encode(symb2freq)
|
||||
print "Symbol\tWeight\tHuffman Code"
|
||||
for p in huff:
|
||||
print "%s\t%s\t%s" % (p[0], symb2freq[p[0]], p[1])
|
||||
113
Task/Huffman-coding/Racket/huffman-coding.rkt
Normal file
113
Task/Huffman-coding/Racket/huffman-coding.rkt
Normal file
|
|
@ -0,0 +1,113 @@
|
|||
#lang racket
|
||||
|
||||
(require data/heap
|
||||
data/bit-vector)
|
||||
|
||||
;; A node is either an interior, or a leaf.
|
||||
;; In either case, they record an item with an associated frequency.
|
||||
(struct node (freq) #:transparent)
|
||||
(struct interior node (left right) #:transparent)
|
||||
(struct leaf node (val) #:transparent)
|
||||
|
||||
;; node<=?: node node -> boolean
|
||||
;; Compares two nodes by frequency.
|
||||
(define (node<=? x y)
|
||||
(<= (node-freq x) (node-freq y)))
|
||||
|
||||
;; We keep a private sentinel-val under our own control.
|
||||
(define sentinel-val (cons 'sentinel 'sentinel))
|
||||
|
||||
;; make-huffman-tree: (listof leaf) -> interior-node
|
||||
;; Makes the huffman tree with basic priority-queue operations.
|
||||
;; Note: we ensure that make-huffman-tree always returns an interior node.
|
||||
(define (make-huffman-tree leaves)
|
||||
(define a-heap (make-heap node<=?))
|
||||
(heap-add-all! a-heap leaves)
|
||||
;; To ensure that we always get tree with at least one interior node,
|
||||
;; we also inject a sentinel leaf node with zero frequency.
|
||||
(heap-add! a-heap (leaf 0 sentinel-val))
|
||||
(for ([i (in-range (length leaves))])
|
||||
(define min-1 (heap-min a-heap))
|
||||
(heap-remove-min! a-heap)
|
||||
(define min-2 (heap-min a-heap))
|
||||
(heap-remove-min! a-heap)
|
||||
(heap-add! a-heap (interior (+ (node-freq min-1) (node-freq min-2))
|
||||
min-1 min-2)))
|
||||
(heap-min a-heap))
|
||||
|
||||
;; string->huffman-tree: string -> node
|
||||
;; Given a string, produces its huffman tree. The leaves hold the characters
|
||||
;; and their relative frequencies.
|
||||
(define (string->huffman-tree str)
|
||||
(define ht (make-hash))
|
||||
(define n (sequence-length str))
|
||||
(for ([ch str])
|
||||
(hash-set! ht ch (add1 (hash-ref ht ch 0))))
|
||||
(make-huffman-tree
|
||||
(for/list ([(k v) (in-hash ht)])
|
||||
(leaf (/ v n) k))))
|
||||
|
||||
;; make-encoder: node -> (string -> bit-vector)
|
||||
;; Given a huffman tree, generates the encoder function.
|
||||
(define (make-encoder a-tree)
|
||||
(define dict (huffman-tree->dictionary a-tree))
|
||||
(lambda (a-str)
|
||||
(list->bit-vector (apply append (for/list ([ch a-str]) (hash-ref dict ch))))))
|
||||
|
||||
;; huffman-tree->dictionary: node -> (hashof val (listof boolean))
|
||||
;; A helper for the encoder: maps characters to their code sequences.
|
||||
(define (huffman-tree->dictionary a-node)
|
||||
(define ht (make-hash))
|
||||
(let loop ([a-node a-node]
|
||||
[path/rev '()])
|
||||
(cond
|
||||
[(interior? a-node)
|
||||
(loop (interior-left a-node) (cons #f path/rev))
|
||||
(loop (interior-right a-node) (cons #t path/rev))]
|
||||
[(leaf? a-node)
|
||||
(unless (eq? (leaf-val a-node) sentinel-val)
|
||||
(hash-set! ht (reverse path/rev) (leaf-val a-node)))]))
|
||||
(for/hash ([(k v) ht])
|
||||
(values v k)))
|
||||
|
||||
;; make-decoder: interior-node -> (bit-vector -> string)
|
||||
;; Generates the decoder function from the tree.
|
||||
(define (make-decoder a-tree)
|
||||
(lambda (a-bitvector)
|
||||
(define-values (decoded/rev _)
|
||||
(for/fold ([decoded/rev '()]
|
||||
[a-node a-tree])
|
||||
([bit a-bitvector])
|
||||
(define next-node
|
||||
(cond
|
||||
[(not bit)
|
||||
(interior-left a-node)]
|
||||
[else
|
||||
(interior-right a-node)]))
|
||||
(cond [(leaf? next-node)
|
||||
(values (cons (leaf-val next-node) decoded/rev)
|
||||
a-tree)]
|
||||
[else
|
||||
(values decoded/rev next-node)])))
|
||||
(apply string (reverse decoded/rev))))
|
||||
|
||||
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
;; Example application:
|
||||
;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;
|
||||
(define msg "this is an example for huffman encoding")
|
||||
|
||||
(define tree (string->huffman-tree msg))
|
||||
|
||||
;; We can print out the mapping for inspection:
|
||||
(huffman-tree->dictionary tree)
|
||||
|
||||
(define encode (make-encoder tree))
|
||||
(define encoded (encode msg))
|
||||
|
||||
;; Here's what the encoded message looks like:
|
||||
(bit-vector->string encoded)
|
||||
|
||||
(define decode (make-decoder tree))
|
||||
;; Here's what the decoded message looks like:
|
||||
(decode encoded)
|
||||
54
Task/Huffman-coding/Ruby/huffman-coding.rb
Normal file
54
Task/Huffman-coding/Ruby/huffman-coding.rb
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
require 'priority_queue'
|
||||
|
||||
def huffman_encoding(str)
|
||||
char_count = Hash.new(0)
|
||||
str.each_char {|c| char_count[c] += 1}
|
||||
|
||||
pq = CPriorityQueue.new
|
||||
# chars with fewest count have highest priority
|
||||
char_count.each {|char, count| pq.push(char, count)}
|
||||
|
||||
while pq.length > 1
|
||||
key1, prio1 = pq.delete_min
|
||||
key2, prio2 = pq.delete_min
|
||||
pq.push([key1, key2], prio1 + prio2)
|
||||
end
|
||||
|
||||
Hash[*generate_encoding(pq.min_key)]
|
||||
end
|
||||
|
||||
def generate_encoding(ary, prefix="")
|
||||
case ary
|
||||
when Array
|
||||
generate_encoding(ary[0], "#{prefix}0") + generate_encoding(ary[1], "#{prefix}1")
|
||||
else
|
||||
[ary, prefix]
|
||||
end
|
||||
end
|
||||
|
||||
def encode(str, encoding)
|
||||
str.each_char.collect {|char| encoding[char]}.join
|
||||
end
|
||||
|
||||
def decode(encoded, encoding)
|
||||
rev_enc = encoding.invert
|
||||
decoded = ""
|
||||
pos = 0
|
||||
while pos < encoded.length
|
||||
key = ""
|
||||
while rev_enc[key].nil?
|
||||
key << encoded[pos]
|
||||
pos += 1
|
||||
end
|
||||
decoded << rev_enc[key]
|
||||
end
|
||||
decoded
|
||||
end
|
||||
|
||||
str = "this is an example for huffman encoding"
|
||||
encoding = huffman_encoding(str)
|
||||
encoding.to_a.sort.each {|x| p x}
|
||||
|
||||
enc = encode(str, encoding)
|
||||
dec = decode(enc, encoding)
|
||||
puts "success!" if str == dec
|
||||
49
Task/Huffman-coding/Scala/huffman-coding.scala
Normal file
49
Task/Huffman-coding/Scala/huffman-coding.scala
Normal file
|
|
@ -0,0 +1,49 @@
|
|||
object Huffman {
|
||||
import scala.collection.mutable.{Map, PriorityQueue}
|
||||
|
||||
sealed abstract class Tree
|
||||
case class Node(left: Tree, right: Tree) extends Tree
|
||||
case class Leaf(c: Char) extends Tree
|
||||
|
||||
def treeOrdering(m: Map[Tree, Int]) = new Ordering[Tree] {
|
||||
def compare(x: Tree, y: Tree) = m(y).compare(m(x))
|
||||
}
|
||||
|
||||
def stringMap(text: String) = text groupBy (x => Leaf(x) : Tree) mapValues (_.length)
|
||||
|
||||
def buildNode(queue: PriorityQueue[Tree], map: Map[Tree,Int]) {
|
||||
val right = queue.dequeue
|
||||
val left = queue.dequeue
|
||||
val node = Node(left, right)
|
||||
map(node) = map(left) + map(right)
|
||||
queue.enqueue(node)
|
||||
}
|
||||
|
||||
def codify(tree: Tree, map: Map[Tree, Int]) = {
|
||||
def recurse(tree: Tree, prefix: String): List[(Char, (Int, String))] = tree match {
|
||||
case Node(left, right) => recurse(left, prefix+"0") ::: recurse(right, prefix+"1")
|
||||
case leaf @ Leaf(c) => c -> ((map(leaf), prefix)) :: Nil
|
||||
}
|
||||
recurse(tree, "")
|
||||
}
|
||||
|
||||
def encode(text: String) = {
|
||||
val map = Map.empty[Tree,Int] ++= stringMap(text)
|
||||
val queue = new PriorityQueue[Tree]()(treeOrdering(map)) ++= map.keysIterator
|
||||
|
||||
while(queue.size > 1) {
|
||||
buildNode(queue, map)
|
||||
}
|
||||
codify(queue.dequeue, map)
|
||||
}
|
||||
|
||||
|
||||
def main(args: Array[String]) {
|
||||
val text = "this is an example for huffman encoding"
|
||||
val code = encode(text)
|
||||
println("Char\tWeight\t\tEncoding")
|
||||
code sortBy (_._2._1) foreach {
|
||||
case (c, (weight, encoding)) => println("%c:\t%3d/%-3d\t\t%s" format (c, weight, text.length, encoding))
|
||||
}
|
||||
}
|
||||
}
|
||||
54
Task/Huffman-coding/Tcl/huffman-coding.tcl
Normal file
54
Task/Huffman-coding/Tcl/huffman-coding.tcl
Normal file
|
|
@ -0,0 +1,54 @@
|
|||
package require Tcl 8.5
|
||||
package require struct::prioqueue
|
||||
|
||||
proc huffmanEncode {str args} {
|
||||
array set opts [concat -dump false $args]
|
||||
|
||||
set charcount [dict create]
|
||||
foreach char [split $str ""] {
|
||||
dict incr charcount $char
|
||||
}
|
||||
|
||||
set pq [struct::prioqueue -dictionary] ;# want lower values to have higher priority
|
||||
dict for {char count} $charcount {
|
||||
$pq put $char $count
|
||||
}
|
||||
|
||||
while {[$pq size] > 1} {
|
||||
lassign [$pq peekpriority 2] p1 p2
|
||||
$pq put [$pq get 2] [expr {$p1 + $p2}]
|
||||
}
|
||||
|
||||
set encoding [walkTree [$pq get]]
|
||||
set map [dict create {*}[lreverse $encoding]]
|
||||
|
||||
if {$opts(-dump)} {
|
||||
foreach key [lsort -command compare [dict keys $map]] {
|
||||
set char [dict get $map $key]
|
||||
puts "$char\t[dict get $charcount $char]\t$key"
|
||||
}
|
||||
}
|
||||
|
||||
return $encoding
|
||||
}
|
||||
|
||||
proc walkTree {tree {prefix ""}} {
|
||||
if {[llength $tree] < 2} {
|
||||
return [list $tree $prefix]
|
||||
}
|
||||
lassign $tree left right
|
||||
return [concat [walkTree $left "${prefix}0"] [walkTree $right "${prefix}1"]]
|
||||
}
|
||||
|
||||
proc compare {a b} {
|
||||
if {[string length $a] < [string length $b]} {return -1}
|
||||
if {[string length $a] > [string length $b]} {return 1}
|
||||
return [string compare $a $b]
|
||||
}
|
||||
|
||||
set str "this is an example for huffman encoding"
|
||||
|
||||
set encoding [huffmanEncode $str -dump true]
|
||||
|
||||
puts $str
|
||||
puts [string map $encoding $str]
|
||||
Loading…
Add table
Add a link
Reference in a new issue