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

32 lines
849 B
Text
Raw Permalink Normal View History

2024-07-13 15:19:22 -07:00
T Element((Int weight, [(Char, String)] symbols))
2023-07-01 11:58:00 -04:00
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]))