Huffman coding: Difference between revisions

Added 11l
(Added Wren)
(Added 11l)
Line 29:
create a program to generate a Huffman encoding for each character as a table.
<br><br>
 
=={{header|11l}}==
{{trans|Python}}
 
<lang 11l>T Element
Int weight
[(Char, String)] symbols
 
F (weight, symbols)
.weight = weight
.symbols = symbols
 
F <(other)
R (.weight, .symbols) < (other.weight, other.symbols)
 
F encode(symb2freq)
V heap = symb2freq.map((sym, wt) -> Element(wt, [(sym, ‘’)]))
minheap:heapify(&heap)
 
L heap.len > 1
V lo = minheap:pop(&heap)
V hi = minheap:pop(&heap)
 
L(&sym) lo.symbols
sym[1] = ‘0’sym[1]
 
L(&sym) hi.symbols
sym[1] = ‘1’sym[1]
 
minheap:push(&heap, Element(lo.weight + hi.weight, lo.symbols [+] hi.symbols))
 
R sorted(minheap:pop(&heap).symbols, key' p -> (p[1].len, p))
 
V txt = ‘this is an example for huffman encoding’
V symb2freq = DefaultDict[Char, Int]()
L(ch) txt
symb2freq[ch]++
 
V huff = encode(symb2freq)
print("Symbol\tWeight\tHuffman Code")
L(p) huff
print("#.\t#.\t#.".format(p[0], symb2freq[p[0]], p[1]))</lang>
 
{{out}}
<pre>
Symbol Weight Huffman Code
6 101
n 4 010
a 3 1001
e 3 1100
f 3 1101
h 2 0001
i 3 1110
m 2 0010
o 2 0011
s 2 0111
g 1 00000
l 1 00001
p 1 01100
r 1 01101
t 1 10000
u 1 10001
x 1 11110
c 1 111110
d 1 111111
</pre>
 
=={{header|Ada}}==
1,463

edits