RosettaCodeData/Task/Huffman-coding/11l/huffman-coding.11l

32 lines
849 B
Plaintext
Raw Permalink Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

T Element((Int weight, [(Char, String)] 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] = 0sym[1]
L(&sym) hi.symbols
sym[1] = 1sym[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]))