Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Port the following code from BBC_Basic to Python with equivalent syntax and logic.
INSTALL @lib$+"SORTSALIB" SortUp% = FN_sortSAinit(0,0) : SortDn% = FN_sortSAinit(1,0) : 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
from heapq import heappush, heappop, heapify from collections import defaultdict def encode(symb2freq): 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 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])
Port the provided BBC_Basic code into Go while preserving the original functionality.
INSTALL @lib$+"SORTSALIB" SortUp% = FN_sortSAinit(0,0) : SortDn% = FN_sortSAinit(1,0) : 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
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 { a := heap.Pop(&trees).(HuffmanTree) b := heap.Pop(&trees).(HuffmanTree) 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: fmt.Printf("%c\t%d\t%s\n", i.value, i.freq, string(prefix)) case HuffmanNode: prefix = append(prefix, '0') printCodes(i.left, prefix) prefix = prefix[:len(prefix)-1] 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) for _, c := range test { symFreqs[c]++ } tree := buildTree(symFreqs) fmt.Println("SYMBOL\tWEIGHT\tHUFFMAN CODE") printCodes(tree, []byte{}) }
Port the following code from Clojure to C with equivalent syntax and logic.
(require '[clojure.pprint :refer :all]) (defn probs [s] (let [freqs (frequencies s) sum (apply + (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] (symbol-map t "")) ([{:keys [symbol priority left right] :as t} code] (if symbol [{:symbol symbol :weight priority :code code}] (concat (symbol-map left (str code \0)) (symbol-map right (str code \1)))))) (defn huffman-encode [items] (-> items probs init-pq huffman-tree symbol-map)) (defn display-huffman-encode [s] (->> s huffman-encode (sort-by :weight >) print-table)) (display-huffman-encode "this is an example for huffman encoding")
#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; 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; int *a = heap->h; while(i < heap->n) { 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; } 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; }
Ensure the translated C# code behaves exactly like the original Clojure snippet.
(require '[clojure.pprint :refer :all]) (defn probs [s] (let [freqs (frequencies s) sum (apply + (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] (symbol-map t "")) ([{:keys [symbol priority left right] :as t} code] (if symbol [{:symbol symbol :weight priority :code code}] (concat (symbol-map left (str code \0)) (symbol-map right (str code \1)))))) (defn huffman-encode [items] (-> items probs init-pq huffman-tree symbol-map)) (defn display-huffman-encode [s] (->> s huffman-encode (sort-by :weight >) print-table)) (display-huffman-encode "this is an example for huffman encoding")
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(); } } }
Ensure the translated C++ code behaves exactly like the original Clojure snippet.
(require '[clojure.pprint :refer :all]) (defn probs [s] (let [freqs (frequencies s) sum (apply + (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] (symbol-map t "")) ([{:keys [symbol priority left right] :as t} code] (if symbol [{:symbol symbol :weight priority :code code}] (concat (symbol-map left (str code \0)) (symbol-map right (str code \1)))))) (defn huffman-encode [items] (-> items probs init-pq huffman-tree symbol-map)) (defn display-huffman-encode [s] (->> s huffman-encode (sort-by :weight >) print-table)) (display-huffman-encode "this is an example for huffman encoding")
#include <iostream> #include <queue> #include <map> #include <climits> #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() { 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; }
Change the following Clojure code into Java without altering its purpose.
(require '[clojure.pprint :refer :all]) (defn probs [s] (let [freqs (frequencies s) sum (apply + (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] (symbol-map t "")) ([{:keys [symbol priority left right] :as t} code] (if symbol [{:symbol symbol :weight priority :code code}] (concat (symbol-map left (str code \0)) (symbol-map right (str code \1)))))) (defn huffman-encode [items] (-> items probs init-pq huffman-tree symbol-map)) (defn display-huffman-encode [s] (->> s huffman-encode (sort-by :weight >) print-table)) (display-huffman-encode "this is an example for huffman encoding")
import java.util.*; abstract class HuffmanTree implements Comparable<HuffmanTree> { public final int frequency; public HuffmanTree(int freq) { frequency = freq; } public int compareTo(HuffmanTree tree) { return frequency - tree.frequency; } } class HuffmanLeaf extends HuffmanTree { public final char value; public HuffmanLeaf(int freq, char val) { super(freq); value = val; } } class HuffmanNode extends HuffmanTree { public final HuffmanTree left, right; public HuffmanNode(HuffmanTree l, HuffmanTree r) { super(l.frequency + r.frequency); left = l; right = r; } } public class HuffmanCode { public static HuffmanTree buildTree(int[] charFreqs) { PriorityQueue<HuffmanTree> trees = new PriorityQueue<HuffmanTree>(); for (int i = 0; i < charFreqs.length; i++) if (charFreqs[i] > 0) trees.offer(new HuffmanLeaf(charFreqs[i], (char)i)); assert trees.size() > 0; while (trees.size() > 1) { HuffmanTree a = trees.poll(); HuffmanTree b = trees.poll(); 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; System.out.println(leaf.value + "\t" + leaf.frequency + "\t" + prefix); } else if (tree instanceof HuffmanNode) { HuffmanNode node = (HuffmanNode)tree; prefix.append('0'); printCodes(node.left, prefix); prefix.deleteCharAt(prefix.length()-1); 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"; int[] charFreqs = new int[256]; for (char c : test.toCharArray()) charFreqs[c]++; HuffmanTree tree = buildTree(charFreqs); System.out.println("SYMBOL\tWEIGHT\tHUFFMAN CODE"); printCodes(tree, new StringBuffer()); } }
Write the same code in Python as shown below in Clojure.
(require '[clojure.pprint :refer :all]) (defn probs [s] (let [freqs (frequencies s) sum (apply + (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] (symbol-map t "")) ([{:keys [symbol priority left right] :as t} code] (if symbol [{:symbol symbol :weight priority :code code}] (concat (symbol-map left (str code \0)) (symbol-map right (str code \1)))))) (defn huffman-encode [items] (-> items probs init-pq huffman-tree symbol-map)) (defn display-huffman-encode [s] (->> s huffman-encode (sort-by :weight >) print-table)) (display-huffman-encode "this is an example for huffman encoding")
from heapq import heappush, heappop, heapify from collections import defaultdict def encode(symb2freq): 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 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])
Produce a functionally identical Go code for the snippet given in Clojure.
(require '[clojure.pprint :refer :all]) (defn probs [s] (let [freqs (frequencies s) sum (apply + (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] (symbol-map t "")) ([{:keys [symbol priority left right] :as t} code] (if symbol [{:symbol symbol :weight priority :code code}] (concat (symbol-map left (str code \0)) (symbol-map right (str code \1)))))) (defn huffman-encode [items] (-> items probs init-pq huffman-tree symbol-map)) (defn display-huffman-encode [s] (->> s huffman-encode (sort-by :weight >) print-table)) (display-huffman-encode "this is an example for huffman encoding")
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 { a := heap.Pop(&trees).(HuffmanTree) b := heap.Pop(&trees).(HuffmanTree) 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: fmt.Printf("%c\t%d\t%s\n", i.value, i.freq, string(prefix)) case HuffmanNode: prefix = append(prefix, '0') printCodes(i.left, prefix) prefix = prefix[:len(prefix)-1] 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) for _, c := range test { symFreqs[c]++ } tree := buildTree(symFreqs) fmt.Println("SYMBOL\tWEIGHT\tHUFFMAN CODE") printCodes(tree, []byte{}) }
Ensure the translated C code behaves exactly like the original Common_Lisp snippet.
(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))))
#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; 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; int *a = heap->h; while(i < heap->n) { 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; } 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; }
Can you help me rewrite this code in C# instead of Common_Lisp, keeping it the same logically?
(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))))
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(); } } }
Generate an equivalent C++ version of this Common_Lisp code.
(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))))
#include <iostream> #include <queue> #include <map> #include <climits> #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() { 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; }
Convert this Common_Lisp snippet to Java and keep its semantics consistent.
(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))))
import java.util.*; abstract class HuffmanTree implements Comparable<HuffmanTree> { public final int frequency; public HuffmanTree(int freq) { frequency = freq; } public int compareTo(HuffmanTree tree) { return frequency - tree.frequency; } } class HuffmanLeaf extends HuffmanTree { public final char value; public HuffmanLeaf(int freq, char val) { super(freq); value = val; } } class HuffmanNode extends HuffmanTree { public final HuffmanTree left, right; public HuffmanNode(HuffmanTree l, HuffmanTree r) { super(l.frequency + r.frequency); left = l; right = r; } } public class HuffmanCode { public static HuffmanTree buildTree(int[] charFreqs) { PriorityQueue<HuffmanTree> trees = new PriorityQueue<HuffmanTree>(); for (int i = 0; i < charFreqs.length; i++) if (charFreqs[i] > 0) trees.offer(new HuffmanLeaf(charFreqs[i], (char)i)); assert trees.size() > 0; while (trees.size() > 1) { HuffmanTree a = trees.poll(); HuffmanTree b = trees.poll(); 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; System.out.println(leaf.value + "\t" + leaf.frequency + "\t" + prefix); } else if (tree instanceof HuffmanNode) { HuffmanNode node = (HuffmanNode)tree; prefix.append('0'); printCodes(node.left, prefix); prefix.deleteCharAt(prefix.length()-1); 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"; int[] charFreqs = new int[256]; for (char c : test.toCharArray()) charFreqs[c]++; HuffmanTree tree = buildTree(charFreqs); System.out.println("SYMBOL\tWEIGHT\tHUFFMAN CODE"); printCodes(tree, new StringBuffer()); } }
Change the following Common_Lisp code into Python without altering its purpose.
(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))))
from heapq import heappush, heappop, heapify from collections import defaultdict def encode(symb2freq): 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 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])
Write a version of this Common_Lisp function in Go with identical behavior.
(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))))
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 { a := heap.Pop(&trees).(HuffmanTree) b := heap.Pop(&trees).(HuffmanTree) 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: fmt.Printf("%c\t%d\t%s\n", i.value, i.freq, string(prefix)) case HuffmanNode: prefix = append(prefix, '0') printCodes(i.left, prefix) prefix = prefix[:len(prefix)-1] 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) for _, c := range test { symFreqs[c]++ } tree := buildTree(symFreqs) fmt.Println("SYMBOL\tWEIGHT\tHUFFMAN CODE") printCodes(tree, []byte{}) }
Change the following D code into C without altering its purpose.
import std.stdio, std.algorithm, std.typecons, std.container, std.array; auto encode(alias eq, R)(Group!(eq, R) 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; lo[1].each!((ref pair) => pair[1] = '0' ~ pair[1]); hi[1].each!((ref pair) => 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() { immutable s = "this is an example for huffman encoding"d; foreach (const p; s.dup.sort().group.encode) writefln("'%s' %s", p[]); }
#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; 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; int *a = heap->h; while(i < heap->n) { 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; } 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; }
Generate a C# translation of this D snippet without changing its computational steps.
import std.stdio, std.algorithm, std.typecons, std.container, std.array; auto encode(alias eq, R)(Group!(eq, R) 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; lo[1].each!((ref pair) => pair[1] = '0' ~ pair[1]); hi[1].each!((ref pair) => 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() { immutable s = "this is an example for huffman encoding"d; foreach (const p; s.dup.sort().group.encode) writefln("'%s' %s", p[]); }
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(); } } }
Preserve the algorithm and functionality while converting the code from D to C++.
import std.stdio, std.algorithm, std.typecons, std.container, std.array; auto encode(alias eq, R)(Group!(eq, R) 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; lo[1].each!((ref pair) => pair[1] = '0' ~ pair[1]); hi[1].each!((ref pair) => 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() { immutable s = "this is an example for huffman encoding"d; foreach (const p; s.dup.sort().group.encode) writefln("'%s' %s", p[]); }
#include <iostream> #include <queue> #include <map> #include <climits> #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() { 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; }
Convert this D snippet to Java and keep its semantics consistent.
import std.stdio, std.algorithm, std.typecons, std.container, std.array; auto encode(alias eq, R)(Group!(eq, R) 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; lo[1].each!((ref pair) => pair[1] = '0' ~ pair[1]); hi[1].each!((ref pair) => 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() { immutable s = "this is an example for huffman encoding"d; foreach (const p; s.dup.sort().group.encode) writefln("'%s' %s", p[]); }
import java.util.*; abstract class HuffmanTree implements Comparable<HuffmanTree> { public final int frequency; public HuffmanTree(int freq) { frequency = freq; } public int compareTo(HuffmanTree tree) { return frequency - tree.frequency; } } class HuffmanLeaf extends HuffmanTree { public final char value; public HuffmanLeaf(int freq, char val) { super(freq); value = val; } } class HuffmanNode extends HuffmanTree { public final HuffmanTree left, right; public HuffmanNode(HuffmanTree l, HuffmanTree r) { super(l.frequency + r.frequency); left = l; right = r; } } public class HuffmanCode { public static HuffmanTree buildTree(int[] charFreqs) { PriorityQueue<HuffmanTree> trees = new PriorityQueue<HuffmanTree>(); for (int i = 0; i < charFreqs.length; i++) if (charFreqs[i] > 0) trees.offer(new HuffmanLeaf(charFreqs[i], (char)i)); assert trees.size() > 0; while (trees.size() > 1) { HuffmanTree a = trees.poll(); HuffmanTree b = trees.poll(); 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; System.out.println(leaf.value + "\t" + leaf.frequency + "\t" + prefix); } else if (tree instanceof HuffmanNode) { HuffmanNode node = (HuffmanNode)tree; prefix.append('0'); printCodes(node.left, prefix); prefix.deleteCharAt(prefix.length()-1); 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"; int[] charFreqs = new int[256]; for (char c : test.toCharArray()) charFreqs[c]++; HuffmanTree tree = buildTree(charFreqs); System.out.println("SYMBOL\tWEIGHT\tHUFFMAN CODE"); printCodes(tree, new StringBuffer()); } }
Transform the following D implementation into Python, maintaining the same output and logic.
import std.stdio, std.algorithm, std.typecons, std.container, std.array; auto encode(alias eq, R)(Group!(eq, R) 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; lo[1].each!((ref pair) => pair[1] = '0' ~ pair[1]); hi[1].each!((ref pair) => 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() { immutable s = "this is an example for huffman encoding"d; foreach (const p; s.dup.sort().group.encode) writefln("'%s' %s", p[]); }
from heapq import heappush, heappop, heapify from collections import defaultdict def encode(symb2freq): 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 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])
Port the provided D code into Go while preserving the original functionality.
import std.stdio, std.algorithm, std.typecons, std.container, std.array; auto encode(alias eq, R)(Group!(eq, R) 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; lo[1].each!((ref pair) => pair[1] = '0' ~ pair[1]); hi[1].each!((ref pair) => 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() { immutable s = "this is an example for huffman encoding"d; foreach (const p; s.dup.sort().group.encode) writefln("'%s' %s", p[]); }
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 { a := heap.Pop(&trees).(HuffmanTree) b := heap.Pop(&trees).(HuffmanTree) 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: fmt.Printf("%c\t%d\t%s\n", i.value, i.freq, string(prefix)) case HuffmanNode: prefix = append(prefix, '0') printCodes(i.left, prefix) prefix = prefix[:len(prefix)-1] 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) for _, c := range test { symFreqs[c]++ } tree := buildTree(symFreqs) fmt.Println("SYMBOL\tWEIGHT\tHUFFMAN CODE") printCodes(tree, []byte{}) }
Generate an equivalent C version of this Erlang code.
-module(huffman). -export([encode/1, decode/2, main/0]). encode(Text) -> Tree = tree(freq_table(Text)), Dict = dict:from_list(codewords(Tree)), Code = << <<(dict:fetch(Char, Dict))/bitstring>> || Char <- Text >>, {Code, Tree, Dict}. decode(Code, Tree) -> decode(Code, Tree, Tree, []). main() -> {Code, Tree, Dict} = encode("this is an example for huffman encoding"), [begin io:format("~s: ",[[Key]]), print_bits(Value) end || {Key, Value} <- lists:sort(dict:to_list(Dict))], io:format("encoded: "), print_bits(Code), io:format("decoded: "), io:format("~s\n",[decode(Code, Tree)]). decode(<<>>, _, _, Result) -> lists:reverse(Result); decode(<<0:1, Rest/bits>>, Tree, {L = {_, _}, _R}, Result) -> decode(<<Rest/bits>>, Tree, L, Result); decode(<<0:1, Rest/bits>>, Tree, {L, _R}, Result) -> decode(<<Rest/bits>>, Tree, Tree, [L | Result]); decode(<<1:1, Rest/bits>>, Tree, {_L, R = {_, _}}, Result) -> decode(<<Rest/bits>>, Tree, R, Result); decode(<<1:1, Rest/bits>>, Tree, {_L, R}, Result) -> decode(<<Rest/bits>>, Tree, Tree, [R | Result]). codewords({L, R}) -> codewords(L, <<0:1>>) ++ codewords(R, <<1:1>>). codewords({L, R}, <<Bits/bits>>) -> codewords(L, <<Bits/bits, 0:1>>) ++ codewords(R, <<Bits/bits, 1:1>>); codewords(Symbol, <<Bits/bitstring>>) -> [{Symbol, Bits}]. tree([{N, _} | []]) -> N; tree(Ns) -> [{N1, C1}, {N2, C2} | Rest] = lists:keysort(2, Ns), tree([{{N1, N2}, C1 + C2} | Rest]). freq_table(Text) -> freq_table(lists:sort(Text), []). freq_table([], Acc) -> Acc; freq_table([S | Rest], Acc) -> {Block, MoreBlocks} = lists:splitwith(fun (X) -> X == S end, Rest), freq_table(MoreBlocks, [{S, 1 + length(Block)} | Acc]). print_bits(<<>>) -> io:format("\n"); print_bits(<<Bit:1, Rest/bitstring>>) -> io:format("~w", [Bit]), print_bits(Rest).
#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; 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; int *a = heap->h; while(i < heap->n) { 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; } 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; }
Port the following code from Erlang to C# with equivalent syntax and logic.
-module(huffman). -export([encode/1, decode/2, main/0]). encode(Text) -> Tree = tree(freq_table(Text)), Dict = dict:from_list(codewords(Tree)), Code = << <<(dict:fetch(Char, Dict))/bitstring>> || Char <- Text >>, {Code, Tree, Dict}. decode(Code, Tree) -> decode(Code, Tree, Tree, []). main() -> {Code, Tree, Dict} = encode("this is an example for huffman encoding"), [begin io:format("~s: ",[[Key]]), print_bits(Value) end || {Key, Value} <- lists:sort(dict:to_list(Dict))], io:format("encoded: "), print_bits(Code), io:format("decoded: "), io:format("~s\n",[decode(Code, Tree)]). decode(<<>>, _, _, Result) -> lists:reverse(Result); decode(<<0:1, Rest/bits>>, Tree, {L = {_, _}, _R}, Result) -> decode(<<Rest/bits>>, Tree, L, Result); decode(<<0:1, Rest/bits>>, Tree, {L, _R}, Result) -> decode(<<Rest/bits>>, Tree, Tree, [L | Result]); decode(<<1:1, Rest/bits>>, Tree, {_L, R = {_, _}}, Result) -> decode(<<Rest/bits>>, Tree, R, Result); decode(<<1:1, Rest/bits>>, Tree, {_L, R}, Result) -> decode(<<Rest/bits>>, Tree, Tree, [R | Result]). codewords({L, R}) -> codewords(L, <<0:1>>) ++ codewords(R, <<1:1>>). codewords({L, R}, <<Bits/bits>>) -> codewords(L, <<Bits/bits, 0:1>>) ++ codewords(R, <<Bits/bits, 1:1>>); codewords(Symbol, <<Bits/bitstring>>) -> [{Symbol, Bits}]. tree([{N, _} | []]) -> N; tree(Ns) -> [{N1, C1}, {N2, C2} | Rest] = lists:keysort(2, Ns), tree([{{N1, N2}, C1 + C2} | Rest]). freq_table(Text) -> freq_table(lists:sort(Text), []). freq_table([], Acc) -> Acc; freq_table([S | Rest], Acc) -> {Block, MoreBlocks} = lists:splitwith(fun (X) -> X == S end, Rest), freq_table(MoreBlocks, [{S, 1 + length(Block)} | Acc]). print_bits(<<>>) -> io:format("\n"); print_bits(<<Bit:1, Rest/bitstring>>) -> io:format("~w", [Bit]), print_bits(Rest).
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(); } } }
Generate a C++ translation of this Erlang snippet without changing its computational steps.
-module(huffman). -export([encode/1, decode/2, main/0]). encode(Text) -> Tree = tree(freq_table(Text)), Dict = dict:from_list(codewords(Tree)), Code = << <<(dict:fetch(Char, Dict))/bitstring>> || Char <- Text >>, {Code, Tree, Dict}. decode(Code, Tree) -> decode(Code, Tree, Tree, []). main() -> {Code, Tree, Dict} = encode("this is an example for huffman encoding"), [begin io:format("~s: ",[[Key]]), print_bits(Value) end || {Key, Value} <- lists:sort(dict:to_list(Dict))], io:format("encoded: "), print_bits(Code), io:format("decoded: "), io:format("~s\n",[decode(Code, Tree)]). decode(<<>>, _, _, Result) -> lists:reverse(Result); decode(<<0:1, Rest/bits>>, Tree, {L = {_, _}, _R}, Result) -> decode(<<Rest/bits>>, Tree, L, Result); decode(<<0:1, Rest/bits>>, Tree, {L, _R}, Result) -> decode(<<Rest/bits>>, Tree, Tree, [L | Result]); decode(<<1:1, Rest/bits>>, Tree, {_L, R = {_, _}}, Result) -> decode(<<Rest/bits>>, Tree, R, Result); decode(<<1:1, Rest/bits>>, Tree, {_L, R}, Result) -> decode(<<Rest/bits>>, Tree, Tree, [R | Result]). codewords({L, R}) -> codewords(L, <<0:1>>) ++ codewords(R, <<1:1>>). codewords({L, R}, <<Bits/bits>>) -> codewords(L, <<Bits/bits, 0:1>>) ++ codewords(R, <<Bits/bits, 1:1>>); codewords(Symbol, <<Bits/bitstring>>) -> [{Symbol, Bits}]. tree([{N, _} | []]) -> N; tree(Ns) -> [{N1, C1}, {N2, C2} | Rest] = lists:keysort(2, Ns), tree([{{N1, N2}, C1 + C2} | Rest]). freq_table(Text) -> freq_table(lists:sort(Text), []). freq_table([], Acc) -> Acc; freq_table([S | Rest], Acc) -> {Block, MoreBlocks} = lists:splitwith(fun (X) -> X == S end, Rest), freq_table(MoreBlocks, [{S, 1 + length(Block)} | Acc]). print_bits(<<>>) -> io:format("\n"); print_bits(<<Bit:1, Rest/bitstring>>) -> io:format("~w", [Bit]), print_bits(Rest).
#include <iostream> #include <queue> #include <map> #include <climits> #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() { 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; }
Produce a language-to-language conversion: from Erlang to Python, same semantics.
-module(huffman). -export([encode/1, decode/2, main/0]). encode(Text) -> Tree = tree(freq_table(Text)), Dict = dict:from_list(codewords(Tree)), Code = << <<(dict:fetch(Char, Dict))/bitstring>> || Char <- Text >>, {Code, Tree, Dict}. decode(Code, Tree) -> decode(Code, Tree, Tree, []). main() -> {Code, Tree, Dict} = encode("this is an example for huffman encoding"), [begin io:format("~s: ",[[Key]]), print_bits(Value) end || {Key, Value} <- lists:sort(dict:to_list(Dict))], io:format("encoded: "), print_bits(Code), io:format("decoded: "), io:format("~s\n",[decode(Code, Tree)]). decode(<<>>, _, _, Result) -> lists:reverse(Result); decode(<<0:1, Rest/bits>>, Tree, {L = {_, _}, _R}, Result) -> decode(<<Rest/bits>>, Tree, L, Result); decode(<<0:1, Rest/bits>>, Tree, {L, _R}, Result) -> decode(<<Rest/bits>>, Tree, Tree, [L | Result]); decode(<<1:1, Rest/bits>>, Tree, {_L, R = {_, _}}, Result) -> decode(<<Rest/bits>>, Tree, R, Result); decode(<<1:1, Rest/bits>>, Tree, {_L, R}, Result) -> decode(<<Rest/bits>>, Tree, Tree, [R | Result]). codewords({L, R}) -> codewords(L, <<0:1>>) ++ codewords(R, <<1:1>>). codewords({L, R}, <<Bits/bits>>) -> codewords(L, <<Bits/bits, 0:1>>) ++ codewords(R, <<Bits/bits, 1:1>>); codewords(Symbol, <<Bits/bitstring>>) -> [{Symbol, Bits}]. tree([{N, _} | []]) -> N; tree(Ns) -> [{N1, C1}, {N2, C2} | Rest] = lists:keysort(2, Ns), tree([{{N1, N2}, C1 + C2} | Rest]). freq_table(Text) -> freq_table(lists:sort(Text), []). freq_table([], Acc) -> Acc; freq_table([S | Rest], Acc) -> {Block, MoreBlocks} = lists:splitwith(fun (X) -> X == S end, Rest), freq_table(MoreBlocks, [{S, 1 + length(Block)} | Acc]). print_bits(<<>>) -> io:format("\n"); print_bits(<<Bit:1, Rest/bitstring>>) -> io:format("~w", [Bit]), print_bits(Rest).
from heapq import heappush, heappop, heapify from collections import defaultdict def encode(symb2freq): 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 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])
Ensure the translated Go code behaves exactly like the original Erlang snippet.
-module(huffman). -export([encode/1, decode/2, main/0]). encode(Text) -> Tree = tree(freq_table(Text)), Dict = dict:from_list(codewords(Tree)), Code = << <<(dict:fetch(Char, Dict))/bitstring>> || Char <- Text >>, {Code, Tree, Dict}. decode(Code, Tree) -> decode(Code, Tree, Tree, []). main() -> {Code, Tree, Dict} = encode("this is an example for huffman encoding"), [begin io:format("~s: ",[[Key]]), print_bits(Value) end || {Key, Value} <- lists:sort(dict:to_list(Dict))], io:format("encoded: "), print_bits(Code), io:format("decoded: "), io:format("~s\n",[decode(Code, Tree)]). decode(<<>>, _, _, Result) -> lists:reverse(Result); decode(<<0:1, Rest/bits>>, Tree, {L = {_, _}, _R}, Result) -> decode(<<Rest/bits>>, Tree, L, Result); decode(<<0:1, Rest/bits>>, Tree, {L, _R}, Result) -> decode(<<Rest/bits>>, Tree, Tree, [L | Result]); decode(<<1:1, Rest/bits>>, Tree, {_L, R = {_, _}}, Result) -> decode(<<Rest/bits>>, Tree, R, Result); decode(<<1:1, Rest/bits>>, Tree, {_L, R}, Result) -> decode(<<Rest/bits>>, Tree, Tree, [R | Result]). codewords({L, R}) -> codewords(L, <<0:1>>) ++ codewords(R, <<1:1>>). codewords({L, R}, <<Bits/bits>>) -> codewords(L, <<Bits/bits, 0:1>>) ++ codewords(R, <<Bits/bits, 1:1>>); codewords(Symbol, <<Bits/bitstring>>) -> [{Symbol, Bits}]. tree([{N, _} | []]) -> N; tree(Ns) -> [{N1, C1}, {N2, C2} | Rest] = lists:keysort(2, Ns), tree([{{N1, N2}, C1 + C2} | Rest]). freq_table(Text) -> freq_table(lists:sort(Text), []). freq_table([], Acc) -> Acc; freq_table([S | Rest], Acc) -> {Block, MoreBlocks} = lists:splitwith(fun (X) -> X == S end, Rest), freq_table(MoreBlocks, [{S, 1 + length(Block)} | Acc]). print_bits(<<>>) -> io:format("\n"); print_bits(<<Bit:1, Rest/bitstring>>) -> io:format("~w", [Bit]), print_bits(Rest).
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 { a := heap.Pop(&trees).(HuffmanTree) b := heap.Pop(&trees).(HuffmanTree) 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: fmt.Printf("%c\t%d\t%s\n", i.value, i.freq, string(prefix)) case HuffmanNode: prefix = append(prefix, '0') printCodes(i.left, prefix) prefix = prefix[:len(prefix)-1] 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) for _, c := range test { symFreqs[c]++ } tree := buildTree(symFreqs) fmt.Println("SYMBOL\tWEIGHT\tHUFFMAN CODE") printCodes(tree, []byte{}) }
Preserve the algorithm and functionality while converting the code from F# to C.
type 'a HuffmanTree = | Leaf of int * 'a | Node of int * 'a HuffmanTree * 'a HuffmanTree let freq = function Leaf (f, _) | Node (f, _, _) -> f let freqCompare a b = compare (freq a) (freq b) let buildTree charFreqs = let leaves = List.map (fun (c,f) -> Leaf (f,c)) charFreqs let freqSort = List.sortWith freqCompare let rec aux = function | [] -> failwith "empty list" | [a] -> a | a::b::tl -> let node = Node(freq a + freq b, a, b) aux (freqSort(node::tl)) aux (freqSort leaves) let rec printTree = function | code, Leaf (f, c) -> printfn "%c\t%d\t%s" c f (String.concat "" (List.rev code)); | code, Node (_, l, r) -> printTree ("0"::code, l); printTree ("1"::code, r) let () = let str = "this is an example for huffman encoding" let charFreqs = str |> Seq.groupBy id |> Seq.map (fun (c, vals) -> (c, Seq.length vals)) |> Map.ofSeq let tree = charFreqs |> Map.toList |> buildTree printfn "Symbol\tWeight\tHuffman code"; printTree ([], tree)
#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; 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; int *a = heap->h; while(i < heap->n) { 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; } 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; }
Ensure the translated C# code behaves exactly like the original F# snippet.
type 'a HuffmanTree = | Leaf of int * 'a | Node of int * 'a HuffmanTree * 'a HuffmanTree let freq = function Leaf (f, _) | Node (f, _, _) -> f let freqCompare a b = compare (freq a) (freq b) let buildTree charFreqs = let leaves = List.map (fun (c,f) -> Leaf (f,c)) charFreqs let freqSort = List.sortWith freqCompare let rec aux = function | [] -> failwith "empty list" | [a] -> a | a::b::tl -> let node = Node(freq a + freq b, a, b) aux (freqSort(node::tl)) aux (freqSort leaves) let rec printTree = function | code, Leaf (f, c) -> printfn "%c\t%d\t%s" c f (String.concat "" (List.rev code)); | code, Node (_, l, r) -> printTree ("0"::code, l); printTree ("1"::code, r) let () = let str = "this is an example for huffman encoding" let charFreqs = str |> Seq.groupBy id |> Seq.map (fun (c, vals) -> (c, Seq.length vals)) |> Map.ofSeq let tree = charFreqs |> Map.toList |> buildTree printfn "Symbol\tWeight\tHuffman code"; printTree ([], tree)
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(); } } }
Preserve the algorithm and functionality while converting the code from F# to C++.
type 'a HuffmanTree = | Leaf of int * 'a | Node of int * 'a HuffmanTree * 'a HuffmanTree let freq = function Leaf (f, _) | Node (f, _, _) -> f let freqCompare a b = compare (freq a) (freq b) let buildTree charFreqs = let leaves = List.map (fun (c,f) -> Leaf (f,c)) charFreqs let freqSort = List.sortWith freqCompare let rec aux = function | [] -> failwith "empty list" | [a] -> a | a::b::tl -> let node = Node(freq a + freq b, a, b) aux (freqSort(node::tl)) aux (freqSort leaves) let rec printTree = function | code, Leaf (f, c) -> printfn "%c\t%d\t%s" c f (String.concat "" (List.rev code)); | code, Node (_, l, r) -> printTree ("0"::code, l); printTree ("1"::code, r) let () = let str = "this is an example for huffman encoding" let charFreqs = str |> Seq.groupBy id |> Seq.map (fun (c, vals) -> (c, Seq.length vals)) |> Map.ofSeq let tree = charFreqs |> Map.toList |> buildTree printfn "Symbol\tWeight\tHuffman code"; printTree ([], tree)
#include <iostream> #include <queue> #include <map> #include <climits> #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() { 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; }
Generate an equivalent Java version of this F# code.
type 'a HuffmanTree = | Leaf of int * 'a | Node of int * 'a HuffmanTree * 'a HuffmanTree let freq = function Leaf (f, _) | Node (f, _, _) -> f let freqCompare a b = compare (freq a) (freq b) let buildTree charFreqs = let leaves = List.map (fun (c,f) -> Leaf (f,c)) charFreqs let freqSort = List.sortWith freqCompare let rec aux = function | [] -> failwith "empty list" | [a] -> a | a::b::tl -> let node = Node(freq a + freq b, a, b) aux (freqSort(node::tl)) aux (freqSort leaves) let rec printTree = function | code, Leaf (f, c) -> printfn "%c\t%d\t%s" c f (String.concat "" (List.rev code)); | code, Node (_, l, r) -> printTree ("0"::code, l); printTree ("1"::code, r) let () = let str = "this is an example for huffman encoding" let charFreqs = str |> Seq.groupBy id |> Seq.map (fun (c, vals) -> (c, Seq.length vals)) |> Map.ofSeq let tree = charFreqs |> Map.toList |> buildTree printfn "Symbol\tWeight\tHuffman code"; printTree ([], tree)
import java.util.*; abstract class HuffmanTree implements Comparable<HuffmanTree> { public final int frequency; public HuffmanTree(int freq) { frequency = freq; } public int compareTo(HuffmanTree tree) { return frequency - tree.frequency; } } class HuffmanLeaf extends HuffmanTree { public final char value; public HuffmanLeaf(int freq, char val) { super(freq); value = val; } } class HuffmanNode extends HuffmanTree { public final HuffmanTree left, right; public HuffmanNode(HuffmanTree l, HuffmanTree r) { super(l.frequency + r.frequency); left = l; right = r; } } public class HuffmanCode { public static HuffmanTree buildTree(int[] charFreqs) { PriorityQueue<HuffmanTree> trees = new PriorityQueue<HuffmanTree>(); for (int i = 0; i < charFreqs.length; i++) if (charFreqs[i] > 0) trees.offer(new HuffmanLeaf(charFreqs[i], (char)i)); assert trees.size() > 0; while (trees.size() > 1) { HuffmanTree a = trees.poll(); HuffmanTree b = trees.poll(); 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; System.out.println(leaf.value + "\t" + leaf.frequency + "\t" + prefix); } else if (tree instanceof HuffmanNode) { HuffmanNode node = (HuffmanNode)tree; prefix.append('0'); printCodes(node.left, prefix); prefix.deleteCharAt(prefix.length()-1); 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"; int[] charFreqs = new int[256]; for (char c : test.toCharArray()) charFreqs[c]++; HuffmanTree tree = buildTree(charFreqs); System.out.println("SYMBOL\tWEIGHT\tHUFFMAN CODE"); printCodes(tree, new StringBuffer()); } }
Can you help me rewrite this code in Python instead of F#, keeping it the same logically?
type 'a HuffmanTree = | Leaf of int * 'a | Node of int * 'a HuffmanTree * 'a HuffmanTree let freq = function Leaf (f, _) | Node (f, _, _) -> f let freqCompare a b = compare (freq a) (freq b) let buildTree charFreqs = let leaves = List.map (fun (c,f) -> Leaf (f,c)) charFreqs let freqSort = List.sortWith freqCompare let rec aux = function | [] -> failwith "empty list" | [a] -> a | a::b::tl -> let node = Node(freq a + freq b, a, b) aux (freqSort(node::tl)) aux (freqSort leaves) let rec printTree = function | code, Leaf (f, c) -> printfn "%c\t%d\t%s" c f (String.concat "" (List.rev code)); | code, Node (_, l, r) -> printTree ("0"::code, l); printTree ("1"::code, r) let () = let str = "this is an example for huffman encoding" let charFreqs = str |> Seq.groupBy id |> Seq.map (fun (c, vals) -> (c, Seq.length vals)) |> Map.ofSeq let tree = charFreqs |> Map.toList |> buildTree printfn "Symbol\tWeight\tHuffman code"; printTree ([], tree)
from heapq import heappush, heappop, heapify from collections import defaultdict def encode(symb2freq): 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 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])
Write a version of this F# function in Go with identical behavior.
type 'a HuffmanTree = | Leaf of int * 'a | Node of int * 'a HuffmanTree * 'a HuffmanTree let freq = function Leaf (f, _) | Node (f, _, _) -> f let freqCompare a b = compare (freq a) (freq b) let buildTree charFreqs = let leaves = List.map (fun (c,f) -> Leaf (f,c)) charFreqs let freqSort = List.sortWith freqCompare let rec aux = function | [] -> failwith "empty list" | [a] -> a | a::b::tl -> let node = Node(freq a + freq b, a, b) aux (freqSort(node::tl)) aux (freqSort leaves) let rec printTree = function | code, Leaf (f, c) -> printfn "%c\t%d\t%s" c f (String.concat "" (List.rev code)); | code, Node (_, l, r) -> printTree ("0"::code, l); printTree ("1"::code, r) let () = let str = "this is an example for huffman encoding" let charFreqs = str |> Seq.groupBy id |> Seq.map (fun (c, vals) -> (c, Seq.length vals)) |> Map.ofSeq let tree = charFreqs |> Map.toList |> buildTree printfn "Symbol\tWeight\tHuffman code"; printTree ([], tree)
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 { a := heap.Pop(&trees).(HuffmanTree) b := heap.Pop(&trees).(HuffmanTree) 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: fmt.Printf("%c\t%d\t%s\n", i.value, i.freq, string(prefix)) case HuffmanNode: prefix = append(prefix, '0') printCodes(i.left, prefix) prefix = prefix[:len(prefix)-1] 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) for _, c := range test { symFreqs[c]++ } tree := buildTree(symFreqs) fmt.Println("SYMBOL\tWEIGHT\tHUFFMAN CODE") printCodes(tree, []byte{}) }
Transform the following Factor implementation into C, maintaining the same output and logic.
USING: kernel sequences combinators accessors assocs math hashtables math.order sorting.slots classes formatting prettyprint ; IN: huffman TUPLE: huffman-node weight element encoding left right ; : <huffman-tnode> ( left right -- huffman ) huffman-node new [ left<< ] [ swap >>right ] bi ; : <huffman-node> ( element -- huffman ) 1 swap f f f huffman-node boa ; <PRIVATE : huffman-gen ( element nodes -- ) 2dup at [ [ [ 1 + ] change-weight ] change-at ] [ [ dup <huffman-node> swap ] dip set-at ] if ; : (huffman) ( nodes seq -- nodes ) dup [ [ huffman-gen ] curry each ] dip ; : (huffman-weight) ( node1 node2 -- weight ) [ weight>> ] dup bi* + ; : (huffman-combine) ( node1 node2 -- node3 ) [ (huffman-weight) ] [ <huffman-tnode> ] 2bi swap >>weight ; : (huffman-tree) ( nodes -- tree ) dup rest empty? [ first ] [ { { weight>> <=> } } sort-by [ rest rest ] [ first ] [ second ] tri (huffman-combine) prefix (huffman-tree) ] if ; recursive : (huffman-leaf?) ( node -- bool ) [ left>> huffman-node instance? ] [ right>> huffman-node instance? ] bi and not ; : (huffman-leaf) ( leaf bit -- ) swap encoding<< ; DEFER: (huffman-encoding) : (huffman-node) ( bit nodes -- ) [ 0 suffix ] [ 1 suffix ] bi [ [ left>> ] [ right>> ] bi ] 2dip [ swap ] dip [ (huffman-encoding) ] 2bi@ ; : (huffman-encoding) ( bit nodes -- ) over (huffman-leaf?) [ (huffman-leaf) ] [ (huffman-node) ] if ; PRIVATE> : huffman-print ( nodes -- ) "Element" "Weight" "Code" "\n%10s\t%10s\t%6s\n" printf { { weight>> >=< } } sort-by [ [ encoding>> ] [ element>> ] [ weight>> ] tri "%8c\t%7d\t\t" printf pprint "\n" printf ] each ; : huffman ( sequence -- nodes ) H{ } clone (huffman) values [ (huffman-tree) { } (huffman-encoding) ] keep ;
#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; 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; int *a = heap->h; while(i < heap->n) { 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; } 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; }
Convert this Factor block to C#, preserving its control flow and logic.
USING: kernel sequences combinators accessors assocs math hashtables math.order sorting.slots classes formatting prettyprint ; IN: huffman TUPLE: huffman-node weight element encoding left right ; : <huffman-tnode> ( left right -- huffman ) huffman-node new [ left<< ] [ swap >>right ] bi ; : <huffman-node> ( element -- huffman ) 1 swap f f f huffman-node boa ; <PRIVATE : huffman-gen ( element nodes -- ) 2dup at [ [ [ 1 + ] change-weight ] change-at ] [ [ dup <huffman-node> swap ] dip set-at ] if ; : (huffman) ( nodes seq -- nodes ) dup [ [ huffman-gen ] curry each ] dip ; : (huffman-weight) ( node1 node2 -- weight ) [ weight>> ] dup bi* + ; : (huffman-combine) ( node1 node2 -- node3 ) [ (huffman-weight) ] [ <huffman-tnode> ] 2bi swap >>weight ; : (huffman-tree) ( nodes -- tree ) dup rest empty? [ first ] [ { { weight>> <=> } } sort-by [ rest rest ] [ first ] [ second ] tri (huffman-combine) prefix (huffman-tree) ] if ; recursive : (huffman-leaf?) ( node -- bool ) [ left>> huffman-node instance? ] [ right>> huffman-node instance? ] bi and not ; : (huffman-leaf) ( leaf bit -- ) swap encoding<< ; DEFER: (huffman-encoding) : (huffman-node) ( bit nodes -- ) [ 0 suffix ] [ 1 suffix ] bi [ [ left>> ] [ right>> ] bi ] 2dip [ swap ] dip [ (huffman-encoding) ] 2bi@ ; : (huffman-encoding) ( bit nodes -- ) over (huffman-leaf?) [ (huffman-leaf) ] [ (huffman-node) ] if ; PRIVATE> : huffman-print ( nodes -- ) "Element" "Weight" "Code" "\n%10s\t%10s\t%6s\n" printf { { weight>> >=< } } sort-by [ [ encoding>> ] [ element>> ] [ weight>> ] tri "%8c\t%7d\t\t" printf pprint "\n" printf ] each ; : huffman ( sequence -- nodes ) H{ } clone (huffman) values [ (huffman-tree) { } (huffman-encoding) ] keep ;
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(); } } }
Port the provided Factor code into C++ while preserving the original functionality.
USING: kernel sequences combinators accessors assocs math hashtables math.order sorting.slots classes formatting prettyprint ; IN: huffman TUPLE: huffman-node weight element encoding left right ; : <huffman-tnode> ( left right -- huffman ) huffman-node new [ left<< ] [ swap >>right ] bi ; : <huffman-node> ( element -- huffman ) 1 swap f f f huffman-node boa ; <PRIVATE : huffman-gen ( element nodes -- ) 2dup at [ [ [ 1 + ] change-weight ] change-at ] [ [ dup <huffman-node> swap ] dip set-at ] if ; : (huffman) ( nodes seq -- nodes ) dup [ [ huffman-gen ] curry each ] dip ; : (huffman-weight) ( node1 node2 -- weight ) [ weight>> ] dup bi* + ; : (huffman-combine) ( node1 node2 -- node3 ) [ (huffman-weight) ] [ <huffman-tnode> ] 2bi swap >>weight ; : (huffman-tree) ( nodes -- tree ) dup rest empty? [ first ] [ { { weight>> <=> } } sort-by [ rest rest ] [ first ] [ second ] tri (huffman-combine) prefix (huffman-tree) ] if ; recursive : (huffman-leaf?) ( node -- bool ) [ left>> huffman-node instance? ] [ right>> huffman-node instance? ] bi and not ; : (huffman-leaf) ( leaf bit -- ) swap encoding<< ; DEFER: (huffman-encoding) : (huffman-node) ( bit nodes -- ) [ 0 suffix ] [ 1 suffix ] bi [ [ left>> ] [ right>> ] bi ] 2dip [ swap ] dip [ (huffman-encoding) ] 2bi@ ; : (huffman-encoding) ( bit nodes -- ) over (huffman-leaf?) [ (huffman-leaf) ] [ (huffman-node) ] if ; PRIVATE> : huffman-print ( nodes -- ) "Element" "Weight" "Code" "\n%10s\t%10s\t%6s\n" printf { { weight>> >=< } } sort-by [ [ encoding>> ] [ element>> ] [ weight>> ] tri "%8c\t%7d\t\t" printf pprint "\n" printf ] each ; : huffman ( sequence -- nodes ) H{ } clone (huffman) values [ (huffman-tree) { } (huffman-encoding) ] keep ;
#include <iostream> #include <queue> #include <map> #include <climits> #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() { 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; }
Keep all operations the same but rewrite the snippet in Java.
USING: kernel sequences combinators accessors assocs math hashtables math.order sorting.slots classes formatting prettyprint ; IN: huffman TUPLE: huffman-node weight element encoding left right ; : <huffman-tnode> ( left right -- huffman ) huffman-node new [ left<< ] [ swap >>right ] bi ; : <huffman-node> ( element -- huffman ) 1 swap f f f huffman-node boa ; <PRIVATE : huffman-gen ( element nodes -- ) 2dup at [ [ [ 1 + ] change-weight ] change-at ] [ [ dup <huffman-node> swap ] dip set-at ] if ; : (huffman) ( nodes seq -- nodes ) dup [ [ huffman-gen ] curry each ] dip ; : (huffman-weight) ( node1 node2 -- weight ) [ weight>> ] dup bi* + ; : (huffman-combine) ( node1 node2 -- node3 ) [ (huffman-weight) ] [ <huffman-tnode> ] 2bi swap >>weight ; : (huffman-tree) ( nodes -- tree ) dup rest empty? [ first ] [ { { weight>> <=> } } sort-by [ rest rest ] [ first ] [ second ] tri (huffman-combine) prefix (huffman-tree) ] if ; recursive : (huffman-leaf?) ( node -- bool ) [ left>> huffman-node instance? ] [ right>> huffman-node instance? ] bi and not ; : (huffman-leaf) ( leaf bit -- ) swap encoding<< ; DEFER: (huffman-encoding) : (huffman-node) ( bit nodes -- ) [ 0 suffix ] [ 1 suffix ] bi [ [ left>> ] [ right>> ] bi ] 2dip [ swap ] dip [ (huffman-encoding) ] 2bi@ ; : (huffman-encoding) ( bit nodes -- ) over (huffman-leaf?) [ (huffman-leaf) ] [ (huffman-node) ] if ; PRIVATE> : huffman-print ( nodes -- ) "Element" "Weight" "Code" "\n%10s\t%10s\t%6s\n" printf { { weight>> >=< } } sort-by [ [ encoding>> ] [ element>> ] [ weight>> ] tri "%8c\t%7d\t\t" printf pprint "\n" printf ] each ; : huffman ( sequence -- nodes ) H{ } clone (huffman) values [ (huffman-tree) { } (huffman-encoding) ] keep ;
import java.util.*; abstract class HuffmanTree implements Comparable<HuffmanTree> { public final int frequency; public HuffmanTree(int freq) { frequency = freq; } public int compareTo(HuffmanTree tree) { return frequency - tree.frequency; } } class HuffmanLeaf extends HuffmanTree { public final char value; public HuffmanLeaf(int freq, char val) { super(freq); value = val; } } class HuffmanNode extends HuffmanTree { public final HuffmanTree left, right; public HuffmanNode(HuffmanTree l, HuffmanTree r) { super(l.frequency + r.frequency); left = l; right = r; } } public class HuffmanCode { public static HuffmanTree buildTree(int[] charFreqs) { PriorityQueue<HuffmanTree> trees = new PriorityQueue<HuffmanTree>(); for (int i = 0; i < charFreqs.length; i++) if (charFreqs[i] > 0) trees.offer(new HuffmanLeaf(charFreqs[i], (char)i)); assert trees.size() > 0; while (trees.size() > 1) { HuffmanTree a = trees.poll(); HuffmanTree b = trees.poll(); 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; System.out.println(leaf.value + "\t" + leaf.frequency + "\t" + prefix); } else if (tree instanceof HuffmanNode) { HuffmanNode node = (HuffmanNode)tree; prefix.append('0'); printCodes(node.left, prefix); prefix.deleteCharAt(prefix.length()-1); 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"; int[] charFreqs = new int[256]; for (char c : test.toCharArray()) charFreqs[c]++; HuffmanTree tree = buildTree(charFreqs); System.out.println("SYMBOL\tWEIGHT\tHUFFMAN CODE"); printCodes(tree, new StringBuffer()); } }
Write a version of this Factor function in Python with identical behavior.
USING: kernel sequences combinators accessors assocs math hashtables math.order sorting.slots classes formatting prettyprint ; IN: huffman TUPLE: huffman-node weight element encoding left right ; : <huffman-tnode> ( left right -- huffman ) huffman-node new [ left<< ] [ swap >>right ] bi ; : <huffman-node> ( element -- huffman ) 1 swap f f f huffman-node boa ; <PRIVATE : huffman-gen ( element nodes -- ) 2dup at [ [ [ 1 + ] change-weight ] change-at ] [ [ dup <huffman-node> swap ] dip set-at ] if ; : (huffman) ( nodes seq -- nodes ) dup [ [ huffman-gen ] curry each ] dip ; : (huffman-weight) ( node1 node2 -- weight ) [ weight>> ] dup bi* + ; : (huffman-combine) ( node1 node2 -- node3 ) [ (huffman-weight) ] [ <huffman-tnode> ] 2bi swap >>weight ; : (huffman-tree) ( nodes -- tree ) dup rest empty? [ first ] [ { { weight>> <=> } } sort-by [ rest rest ] [ first ] [ second ] tri (huffman-combine) prefix (huffman-tree) ] if ; recursive : (huffman-leaf?) ( node -- bool ) [ left>> huffman-node instance? ] [ right>> huffman-node instance? ] bi and not ; : (huffman-leaf) ( leaf bit -- ) swap encoding<< ; DEFER: (huffman-encoding) : (huffman-node) ( bit nodes -- ) [ 0 suffix ] [ 1 suffix ] bi [ [ left>> ] [ right>> ] bi ] 2dip [ swap ] dip [ (huffman-encoding) ] 2bi@ ; : (huffman-encoding) ( bit nodes -- ) over (huffman-leaf?) [ (huffman-leaf) ] [ (huffman-node) ] if ; PRIVATE> : huffman-print ( nodes -- ) "Element" "Weight" "Code" "\n%10s\t%10s\t%6s\n" printf { { weight>> >=< } } sort-by [ [ encoding>> ] [ element>> ] [ weight>> ] tri "%8c\t%7d\t\t" printf pprint "\n" printf ] each ; : huffman ( sequence -- nodes ) H{ } clone (huffman) values [ (huffman-tree) { } (huffman-encoding) ] keep ;
from heapq import heappush, heappop, heapify from collections import defaultdict def encode(symb2freq): 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 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])
Convert the following code from Factor to Go, ensuring the logic remains intact.
USING: kernel sequences combinators accessors assocs math hashtables math.order sorting.slots classes formatting prettyprint ; IN: huffman TUPLE: huffman-node weight element encoding left right ; : <huffman-tnode> ( left right -- huffman ) huffman-node new [ left<< ] [ swap >>right ] bi ; : <huffman-node> ( element -- huffman ) 1 swap f f f huffman-node boa ; <PRIVATE : huffman-gen ( element nodes -- ) 2dup at [ [ [ 1 + ] change-weight ] change-at ] [ [ dup <huffman-node> swap ] dip set-at ] if ; : (huffman) ( nodes seq -- nodes ) dup [ [ huffman-gen ] curry each ] dip ; : (huffman-weight) ( node1 node2 -- weight ) [ weight>> ] dup bi* + ; : (huffman-combine) ( node1 node2 -- node3 ) [ (huffman-weight) ] [ <huffman-tnode> ] 2bi swap >>weight ; : (huffman-tree) ( nodes -- tree ) dup rest empty? [ first ] [ { { weight>> <=> } } sort-by [ rest rest ] [ first ] [ second ] tri (huffman-combine) prefix (huffman-tree) ] if ; recursive : (huffman-leaf?) ( node -- bool ) [ left>> huffman-node instance? ] [ right>> huffman-node instance? ] bi and not ; : (huffman-leaf) ( leaf bit -- ) swap encoding<< ; DEFER: (huffman-encoding) : (huffman-node) ( bit nodes -- ) [ 0 suffix ] [ 1 suffix ] bi [ [ left>> ] [ right>> ] bi ] 2dip [ swap ] dip [ (huffman-encoding) ] 2bi@ ; : (huffman-encoding) ( bit nodes -- ) over (huffman-leaf?) [ (huffman-leaf) ] [ (huffman-node) ] if ; PRIVATE> : huffman-print ( nodes -- ) "Element" "Weight" "Code" "\n%10s\t%10s\t%6s\n" printf { { weight>> >=< } } sort-by [ [ encoding>> ] [ element>> ] [ weight>> ] tri "%8c\t%7d\t\t" printf pprint "\n" printf ] each ; : huffman ( sequence -- nodes ) H{ } clone (huffman) values [ (huffman-tree) { } (huffman-encoding) ] keep ;
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 { a := heap.Pop(&trees).(HuffmanTree) b := heap.Pop(&trees).(HuffmanTree) 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: fmt.Printf("%c\t%d\t%s\n", i.value, i.freq, string(prefix)) case HuffmanNode: prefix = append(prefix, '0') printCodes(i.left, prefix) prefix = prefix[:len(prefix)-1] 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) for _, c := range test { symFreqs[c]++ } tree := buildTree(symFreqs) fmt.Println("SYMBOL\tWEIGHT\tHUFFMAN CODE") printCodes(tree, []byte{}) }
Maintain the same structure and functionality when rewriting this code in C#.
module huffman implicit none type node character (len=1 ), allocatable :: sym(:) character (len=10), allocatable :: code(:) integer :: freq contains procedure :: show => show_node end type type queue type(node), allocatable :: buf(:) integer :: n = 0 contains procedure :: extractmin procedure :: append procedure :: siftdown end type contains subroutine siftdown(this, a) class (queue) :: this integer :: a, parent, child associate (x => this%buf) parent = a do while(parent*2 <= this%n) child = parent*2 if (child + 1 <= this%n) then if (x(child+1)%freq < x(child)%freq ) then child = child +1 end if end if if (x(parent)%freq > x(child)%freq) then x([child, parent]) = x([parent, child]) parent = child else exit end if end do end associate end subroutine function extractmin(this) result (res) class(queue) :: this type(node) :: res res = this%buf(1) this%buf(1) = this%buf(this%n) this%n = this%n - 1 call this%siftdown(1) end function subroutine append(this, x) class(queue), intent(inout) :: this type(node) :: x type(node), allocatable :: tmp(:) integer :: i this%n = this%n +1 if (.not.allocated(this%buf)) allocate(this%buf(1)) if (size(this%buf)<this%n) then allocate(tmp(2*size(this%buf))) tmp(1:this%n-1) = this%buf call move_alloc(tmp, this%buf) end if this%buf(this%n) = x i = this%n do i = i / 2 if (i==0) exit call this%siftdown(i) end do end subroutine function join(a, b) result(c) type(node) :: a, b, c integer :: i, n, n1 n1 = size(a%sym) n = n1 + size(b%sym) c%freq = a%freq + b%freq allocate (c%sym(n), c%code(n)) do i = 1, n1 c%sym(i) = a%sym(i) c%code(i) = "0" // trim(a%code(i)) end do do i = 1, size(b%sym) c%sym(i+n1) = b%sym(i) c%code(i+n1) = "1" // trim(b%code(i)) end do end function subroutine show_node(this) class(node) :: this integer :: i write(*, "(*(g0,'-> ',g0,:,', '))", advance="no") & (this%sym(i), trim(this%code(i)), i=1,size(this%sym)) print * end subroutine function create(letter, freq) result (this) character :: letter integer :: freq type(node) :: this allocate(this%sym(1), this%code(1)) this%sym(1) = letter ; this%code(1) = "" this%freq = freq end function end module program main use huffman character (len=*), parameter :: txt = & "this is an example for huffman encoding" integer :: i, freq(0:255) = 0 type(queue) :: Q type(node) :: x do i = 1, len(txt) freq(ichar(txt(i:i))) = freq(ichar(txt(i:i))) + 1 end do do i = 0, 255 if (freq(i)>0) then call Q%append(create(char(i), freq(i))) end if end do do i = 1, Q%n-1 call Q%append(join(Q%extractmin(),Q%extractmin())) end do x = Q%extractmin() call x%show() do i = 1, len(txt) do k = 1, size(x%sym) if (x%sym(k)==txt(i:i)) exit end do write (*, "(a,'|')", advance="no") trim(x%code(k)) end do print * end program
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(); } } }
Change the programming language of this snippet from Fortran to C++ without modifying what it does.
module huffman implicit none type node character (len=1 ), allocatable :: sym(:) character (len=10), allocatable :: code(:) integer :: freq contains procedure :: show => show_node end type type queue type(node), allocatable :: buf(:) integer :: n = 0 contains procedure :: extractmin procedure :: append procedure :: siftdown end type contains subroutine siftdown(this, a) class (queue) :: this integer :: a, parent, child associate (x => this%buf) parent = a do while(parent*2 <= this%n) child = parent*2 if (child + 1 <= this%n) then if (x(child+1)%freq < x(child)%freq ) then child = child +1 end if end if if (x(parent)%freq > x(child)%freq) then x([child, parent]) = x([parent, child]) parent = child else exit end if end do end associate end subroutine function extractmin(this) result (res) class(queue) :: this type(node) :: res res = this%buf(1) this%buf(1) = this%buf(this%n) this%n = this%n - 1 call this%siftdown(1) end function subroutine append(this, x) class(queue), intent(inout) :: this type(node) :: x type(node), allocatable :: tmp(:) integer :: i this%n = this%n +1 if (.not.allocated(this%buf)) allocate(this%buf(1)) if (size(this%buf)<this%n) then allocate(tmp(2*size(this%buf))) tmp(1:this%n-1) = this%buf call move_alloc(tmp, this%buf) end if this%buf(this%n) = x i = this%n do i = i / 2 if (i==0) exit call this%siftdown(i) end do end subroutine function join(a, b) result(c) type(node) :: a, b, c integer :: i, n, n1 n1 = size(a%sym) n = n1 + size(b%sym) c%freq = a%freq + b%freq allocate (c%sym(n), c%code(n)) do i = 1, n1 c%sym(i) = a%sym(i) c%code(i) = "0" // trim(a%code(i)) end do do i = 1, size(b%sym) c%sym(i+n1) = b%sym(i) c%code(i+n1) = "1" // trim(b%code(i)) end do end function subroutine show_node(this) class(node) :: this integer :: i write(*, "(*(g0,'-> ',g0,:,', '))", advance="no") & (this%sym(i), trim(this%code(i)), i=1,size(this%sym)) print * end subroutine function create(letter, freq) result (this) character :: letter integer :: freq type(node) :: this allocate(this%sym(1), this%code(1)) this%sym(1) = letter ; this%code(1) = "" this%freq = freq end function end module program main use huffman character (len=*), parameter :: txt = & "this is an example for huffman encoding" integer :: i, freq(0:255) = 0 type(queue) :: Q type(node) :: x do i = 1, len(txt) freq(ichar(txt(i:i))) = freq(ichar(txt(i:i))) + 1 end do do i = 0, 255 if (freq(i)>0) then call Q%append(create(char(i), freq(i))) end if end do do i = 1, Q%n-1 call Q%append(join(Q%extractmin(),Q%extractmin())) end do x = Q%extractmin() call x%show() do i = 1, len(txt) do k = 1, size(x%sym) if (x%sym(k)==txt(i:i)) exit end do write (*, "(a,'|')", advance="no") trim(x%code(k)) end do print * end program
#include <iostream> #include <queue> #include <map> #include <climits> #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() { 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; }
Write the same algorithm in C as shown in this Fortran implementation.
module huffman implicit none type node character (len=1 ), allocatable :: sym(:) character (len=10), allocatable :: code(:) integer :: freq contains procedure :: show => show_node end type type queue type(node), allocatable :: buf(:) integer :: n = 0 contains procedure :: extractmin procedure :: append procedure :: siftdown end type contains subroutine siftdown(this, a) class (queue) :: this integer :: a, parent, child associate (x => this%buf) parent = a do while(parent*2 <= this%n) child = parent*2 if (child + 1 <= this%n) then if (x(child+1)%freq < x(child)%freq ) then child = child +1 end if end if if (x(parent)%freq > x(child)%freq) then x([child, parent]) = x([parent, child]) parent = child else exit end if end do end associate end subroutine function extractmin(this) result (res) class(queue) :: this type(node) :: res res = this%buf(1) this%buf(1) = this%buf(this%n) this%n = this%n - 1 call this%siftdown(1) end function subroutine append(this, x) class(queue), intent(inout) :: this type(node) :: x type(node), allocatable :: tmp(:) integer :: i this%n = this%n +1 if (.not.allocated(this%buf)) allocate(this%buf(1)) if (size(this%buf)<this%n) then allocate(tmp(2*size(this%buf))) tmp(1:this%n-1) = this%buf call move_alloc(tmp, this%buf) end if this%buf(this%n) = x i = this%n do i = i / 2 if (i==0) exit call this%siftdown(i) end do end subroutine function join(a, b) result(c) type(node) :: a, b, c integer :: i, n, n1 n1 = size(a%sym) n = n1 + size(b%sym) c%freq = a%freq + b%freq allocate (c%sym(n), c%code(n)) do i = 1, n1 c%sym(i) = a%sym(i) c%code(i) = "0" // trim(a%code(i)) end do do i = 1, size(b%sym) c%sym(i+n1) = b%sym(i) c%code(i+n1) = "1" // trim(b%code(i)) end do end function subroutine show_node(this) class(node) :: this integer :: i write(*, "(*(g0,'-> ',g0,:,', '))", advance="no") & (this%sym(i), trim(this%code(i)), i=1,size(this%sym)) print * end subroutine function create(letter, freq) result (this) character :: letter integer :: freq type(node) :: this allocate(this%sym(1), this%code(1)) this%sym(1) = letter ; this%code(1) = "" this%freq = freq end function end module program main use huffman character (len=*), parameter :: txt = & "this is an example for huffman encoding" integer :: i, freq(0:255) = 0 type(queue) :: Q type(node) :: x do i = 1, len(txt) freq(ichar(txt(i:i))) = freq(ichar(txt(i:i))) + 1 end do do i = 0, 255 if (freq(i)>0) then call Q%append(create(char(i), freq(i))) end if end do do i = 1, Q%n-1 call Q%append(join(Q%extractmin(),Q%extractmin())) end do x = Q%extractmin() call x%show() do i = 1, len(txt) do k = 1, size(x%sym) if (x%sym(k)==txt(i:i)) exit end do write (*, "(a,'|')", advance="no") trim(x%code(k)) end do print * end program
#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; 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; int *a = heap->h; while(i < heap->n) { 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; } 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; }
Produce a functionally identical Go code for the snippet given in Fortran.
module huffman implicit none type node character (len=1 ), allocatable :: sym(:) character (len=10), allocatable :: code(:) integer :: freq contains procedure :: show => show_node end type type queue type(node), allocatable :: buf(:) integer :: n = 0 contains procedure :: extractmin procedure :: append procedure :: siftdown end type contains subroutine siftdown(this, a) class (queue) :: this integer :: a, parent, child associate (x => this%buf) parent = a do while(parent*2 <= this%n) child = parent*2 if (child + 1 <= this%n) then if (x(child+1)%freq < x(child)%freq ) then child = child +1 end if end if if (x(parent)%freq > x(child)%freq) then x([child, parent]) = x([parent, child]) parent = child else exit end if end do end associate end subroutine function extractmin(this) result (res) class(queue) :: this type(node) :: res res = this%buf(1) this%buf(1) = this%buf(this%n) this%n = this%n - 1 call this%siftdown(1) end function subroutine append(this, x) class(queue), intent(inout) :: this type(node) :: x type(node), allocatable :: tmp(:) integer :: i this%n = this%n +1 if (.not.allocated(this%buf)) allocate(this%buf(1)) if (size(this%buf)<this%n) then allocate(tmp(2*size(this%buf))) tmp(1:this%n-1) = this%buf call move_alloc(tmp, this%buf) end if this%buf(this%n) = x i = this%n do i = i / 2 if (i==0) exit call this%siftdown(i) end do end subroutine function join(a, b) result(c) type(node) :: a, b, c integer :: i, n, n1 n1 = size(a%sym) n = n1 + size(b%sym) c%freq = a%freq + b%freq allocate (c%sym(n), c%code(n)) do i = 1, n1 c%sym(i) = a%sym(i) c%code(i) = "0" // trim(a%code(i)) end do do i = 1, size(b%sym) c%sym(i+n1) = b%sym(i) c%code(i+n1) = "1" // trim(b%code(i)) end do end function subroutine show_node(this) class(node) :: this integer :: i write(*, "(*(g0,'-> ',g0,:,', '))", advance="no") & (this%sym(i), trim(this%code(i)), i=1,size(this%sym)) print * end subroutine function create(letter, freq) result (this) character :: letter integer :: freq type(node) :: this allocate(this%sym(1), this%code(1)) this%sym(1) = letter ; this%code(1) = "" this%freq = freq end function end module program main use huffman character (len=*), parameter :: txt = & "this is an example for huffman encoding" integer :: i, freq(0:255) = 0 type(queue) :: Q type(node) :: x do i = 1, len(txt) freq(ichar(txt(i:i))) = freq(ichar(txt(i:i))) + 1 end do do i = 0, 255 if (freq(i)>0) then call Q%append(create(char(i), freq(i))) end if end do do i = 1, Q%n-1 call Q%append(join(Q%extractmin(),Q%extractmin())) end do x = Q%extractmin() call x%show() do i = 1, len(txt) do k = 1, size(x%sym) if (x%sym(k)==txt(i:i)) exit end do write (*, "(a,'|')", advance="no") trim(x%code(k)) end do print * end program
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 { a := heap.Pop(&trees).(HuffmanTree) b := heap.Pop(&trees).(HuffmanTree) 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: fmt.Printf("%c\t%d\t%s\n", i.value, i.freq, string(prefix)) case HuffmanNode: prefix = append(prefix, '0') printCodes(i.left, prefix) prefix = prefix[:len(prefix)-1] 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) for _, c := range test { symFreqs[c]++ } tree := buildTree(symFreqs) fmt.Println("SYMBOL\tWEIGHT\tHUFFMAN CODE") printCodes(tree, []byte{}) }
Produce a functionally identical Java code for the snippet given in Fortran.
module huffman implicit none type node character (len=1 ), allocatable :: sym(:) character (len=10), allocatable :: code(:) integer :: freq contains procedure :: show => show_node end type type queue type(node), allocatable :: buf(:) integer :: n = 0 contains procedure :: extractmin procedure :: append procedure :: siftdown end type contains subroutine siftdown(this, a) class (queue) :: this integer :: a, parent, child associate (x => this%buf) parent = a do while(parent*2 <= this%n) child = parent*2 if (child + 1 <= this%n) then if (x(child+1)%freq < x(child)%freq ) then child = child +1 end if end if if (x(parent)%freq > x(child)%freq) then x([child, parent]) = x([parent, child]) parent = child else exit end if end do end associate end subroutine function extractmin(this) result (res) class(queue) :: this type(node) :: res res = this%buf(1) this%buf(1) = this%buf(this%n) this%n = this%n - 1 call this%siftdown(1) end function subroutine append(this, x) class(queue), intent(inout) :: this type(node) :: x type(node), allocatable :: tmp(:) integer :: i this%n = this%n +1 if (.not.allocated(this%buf)) allocate(this%buf(1)) if (size(this%buf)<this%n) then allocate(tmp(2*size(this%buf))) tmp(1:this%n-1) = this%buf call move_alloc(tmp, this%buf) end if this%buf(this%n) = x i = this%n do i = i / 2 if (i==0) exit call this%siftdown(i) end do end subroutine function join(a, b) result(c) type(node) :: a, b, c integer :: i, n, n1 n1 = size(a%sym) n = n1 + size(b%sym) c%freq = a%freq + b%freq allocate (c%sym(n), c%code(n)) do i = 1, n1 c%sym(i) = a%sym(i) c%code(i) = "0" // trim(a%code(i)) end do do i = 1, size(b%sym) c%sym(i+n1) = b%sym(i) c%code(i+n1) = "1" // trim(b%code(i)) end do end function subroutine show_node(this) class(node) :: this integer :: i write(*, "(*(g0,'-> ',g0,:,', '))", advance="no") & (this%sym(i), trim(this%code(i)), i=1,size(this%sym)) print * end subroutine function create(letter, freq) result (this) character :: letter integer :: freq type(node) :: this allocate(this%sym(1), this%code(1)) this%sym(1) = letter ; this%code(1) = "" this%freq = freq end function end module program main use huffman character (len=*), parameter :: txt = & "this is an example for huffman encoding" integer :: i, freq(0:255) = 0 type(queue) :: Q type(node) :: x do i = 1, len(txt) freq(ichar(txt(i:i))) = freq(ichar(txt(i:i))) + 1 end do do i = 0, 255 if (freq(i)>0) then call Q%append(create(char(i), freq(i))) end if end do do i = 1, Q%n-1 call Q%append(join(Q%extractmin(),Q%extractmin())) end do x = Q%extractmin() call x%show() do i = 1, len(txt) do k = 1, size(x%sym) if (x%sym(k)==txt(i:i)) exit end do write (*, "(a,'|')", advance="no") trim(x%code(k)) end do print * end program
import java.util.*; abstract class HuffmanTree implements Comparable<HuffmanTree> { public final int frequency; public HuffmanTree(int freq) { frequency = freq; } public int compareTo(HuffmanTree tree) { return frequency - tree.frequency; } } class HuffmanLeaf extends HuffmanTree { public final char value; public HuffmanLeaf(int freq, char val) { super(freq); value = val; } } class HuffmanNode extends HuffmanTree { public final HuffmanTree left, right; public HuffmanNode(HuffmanTree l, HuffmanTree r) { super(l.frequency + r.frequency); left = l; right = r; } } public class HuffmanCode { public static HuffmanTree buildTree(int[] charFreqs) { PriorityQueue<HuffmanTree> trees = new PriorityQueue<HuffmanTree>(); for (int i = 0; i < charFreqs.length; i++) if (charFreqs[i] > 0) trees.offer(new HuffmanLeaf(charFreqs[i], (char)i)); assert trees.size() > 0; while (trees.size() > 1) { HuffmanTree a = trees.poll(); HuffmanTree b = trees.poll(); 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; System.out.println(leaf.value + "\t" + leaf.frequency + "\t" + prefix); } else if (tree instanceof HuffmanNode) { HuffmanNode node = (HuffmanNode)tree; prefix.append('0'); printCodes(node.left, prefix); prefix.deleteCharAt(prefix.length()-1); 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"; int[] charFreqs = new int[256]; for (char c : test.toCharArray()) charFreqs[c]++; HuffmanTree tree = buildTree(charFreqs); System.out.println("SYMBOL\tWEIGHT\tHUFFMAN CODE"); printCodes(tree, new StringBuffer()); } }
Produce a functionally identical Python code for the snippet given in Fortran.
module huffman implicit none type node character (len=1 ), allocatable :: sym(:) character (len=10), allocatable :: code(:) integer :: freq contains procedure :: show => show_node end type type queue type(node), allocatable :: buf(:) integer :: n = 0 contains procedure :: extractmin procedure :: append procedure :: siftdown end type contains subroutine siftdown(this, a) class (queue) :: this integer :: a, parent, child associate (x => this%buf) parent = a do while(parent*2 <= this%n) child = parent*2 if (child + 1 <= this%n) then if (x(child+1)%freq < x(child)%freq ) then child = child +1 end if end if if (x(parent)%freq > x(child)%freq) then x([child, parent]) = x([parent, child]) parent = child else exit end if end do end associate end subroutine function extractmin(this) result (res) class(queue) :: this type(node) :: res res = this%buf(1) this%buf(1) = this%buf(this%n) this%n = this%n - 1 call this%siftdown(1) end function subroutine append(this, x) class(queue), intent(inout) :: this type(node) :: x type(node), allocatable :: tmp(:) integer :: i this%n = this%n +1 if (.not.allocated(this%buf)) allocate(this%buf(1)) if (size(this%buf)<this%n) then allocate(tmp(2*size(this%buf))) tmp(1:this%n-1) = this%buf call move_alloc(tmp, this%buf) end if this%buf(this%n) = x i = this%n do i = i / 2 if (i==0) exit call this%siftdown(i) end do end subroutine function join(a, b) result(c) type(node) :: a, b, c integer :: i, n, n1 n1 = size(a%sym) n = n1 + size(b%sym) c%freq = a%freq + b%freq allocate (c%sym(n), c%code(n)) do i = 1, n1 c%sym(i) = a%sym(i) c%code(i) = "0" // trim(a%code(i)) end do do i = 1, size(b%sym) c%sym(i+n1) = b%sym(i) c%code(i+n1) = "1" // trim(b%code(i)) end do end function subroutine show_node(this) class(node) :: this integer :: i write(*, "(*(g0,'-> ',g0,:,', '))", advance="no") & (this%sym(i), trim(this%code(i)), i=1,size(this%sym)) print * end subroutine function create(letter, freq) result (this) character :: letter integer :: freq type(node) :: this allocate(this%sym(1), this%code(1)) this%sym(1) = letter ; this%code(1) = "" this%freq = freq end function end module program main use huffman character (len=*), parameter :: txt = & "this is an example for huffman encoding" integer :: i, freq(0:255) = 0 type(queue) :: Q type(node) :: x do i = 1, len(txt) freq(ichar(txt(i:i))) = freq(ichar(txt(i:i))) + 1 end do do i = 0, 255 if (freq(i)>0) then call Q%append(create(char(i), freq(i))) end if end do do i = 1, Q%n-1 call Q%append(join(Q%extractmin(),Q%extractmin())) end do x = Q%extractmin() call x%show() do i = 1, len(txt) do k = 1, size(x%sym) if (x%sym(k)==txt(i:i)) exit end do write (*, "(a,'|')", advance="no") trim(x%code(k)) end do print * end program
from heapq import heappush, heappop, heapify from collections import defaultdict def encode(symb2freq): 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 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])
Produce a functionally identical PHP code for the snippet given in Fortran.
module huffman implicit none type node character (len=1 ), allocatable :: sym(:) character (len=10), allocatable :: code(:) integer :: freq contains procedure :: show => show_node end type type queue type(node), allocatable :: buf(:) integer :: n = 0 contains procedure :: extractmin procedure :: append procedure :: siftdown end type contains subroutine siftdown(this, a) class (queue) :: this integer :: a, parent, child associate (x => this%buf) parent = a do while(parent*2 <= this%n) child = parent*2 if (child + 1 <= this%n) then if (x(child+1)%freq < x(child)%freq ) then child = child +1 end if end if if (x(parent)%freq > x(child)%freq) then x([child, parent]) = x([parent, child]) parent = child else exit end if end do end associate end subroutine function extractmin(this) result (res) class(queue) :: this type(node) :: res res = this%buf(1) this%buf(1) = this%buf(this%n) this%n = this%n - 1 call this%siftdown(1) end function subroutine append(this, x) class(queue), intent(inout) :: this type(node) :: x type(node), allocatable :: tmp(:) integer :: i this%n = this%n +1 if (.not.allocated(this%buf)) allocate(this%buf(1)) if (size(this%buf)<this%n) then allocate(tmp(2*size(this%buf))) tmp(1:this%n-1) = this%buf call move_alloc(tmp, this%buf) end if this%buf(this%n) = x i = this%n do i = i / 2 if (i==0) exit call this%siftdown(i) end do end subroutine function join(a, b) result(c) type(node) :: a, b, c integer :: i, n, n1 n1 = size(a%sym) n = n1 + size(b%sym) c%freq = a%freq + b%freq allocate (c%sym(n), c%code(n)) do i = 1, n1 c%sym(i) = a%sym(i) c%code(i) = "0" // trim(a%code(i)) end do do i = 1, size(b%sym) c%sym(i+n1) = b%sym(i) c%code(i+n1) = "1" // trim(b%code(i)) end do end function subroutine show_node(this) class(node) :: this integer :: i write(*, "(*(g0,'-> ',g0,:,', '))", advance="no") & (this%sym(i), trim(this%code(i)), i=1,size(this%sym)) print * end subroutine function create(letter, freq) result (this) character :: letter integer :: freq type(node) :: this allocate(this%sym(1), this%code(1)) this%sym(1) = letter ; this%code(1) = "" this%freq = freq end function end module program main use huffman character (len=*), parameter :: txt = & "this is an example for huffman encoding" integer :: i, freq(0:255) = 0 type(queue) :: Q type(node) :: x do i = 1, len(txt) freq(ichar(txt(i:i))) = freq(ichar(txt(i:i))) + 1 end do do i = 0, 255 if (freq(i)>0) then call Q%append(create(char(i), freq(i))) end if end do do i = 1, Q%n-1 call Q%append(join(Q%extractmin(),Q%extractmin())) end do x = Q%extractmin() call x%show() do i = 1, len(txt) do k = 1, size(x%sym) if (x%sym(k)==txt(i:i)) exit end do write (*, "(a,'|')", advance="no") trim(x%code(k)) end do print * end program
<?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"; ?>
Please provide an equivalent version of this Groovy code in C.
import groovy.transform.* @Canonical @Sortable(includes = ['freq', 'letter']) class Node { String letter int freq Node left Node right boolean isLeaf() { left == null && right == null } } Map correspondance(Node n, Map corresp = [:], String prefix = '') { if (n.isLeaf()) { corresp[n.letter] = prefix ?: '0' } else { correspondance(n.left, corresp, prefix + '0') correspondance(n.right, corresp, prefix + '1') } return corresp } Map huffmanCode(String message) { def queue = message.toList().countBy { it } .collect { String letter, int freq -> new Node(letter, freq) } as TreeSet while(queue.size() > 1) { def (nodeLeft, nodeRight) = [queue.pollFirst(), queue.pollFirst()] queue << new Node( freq: nodeLeft.freq + nodeRight.freq, letter: nodeLeft.letter + nodeRight.letter, left: nodeLeft, right: nodeRight ) } return correspondance(queue.pollFirst()) } String encode(CharSequence msg, Map codeTable) { msg.collect { codeTable[it] }.join() } String decode(String codedMsg, Map codeTable, String decoded = '') { def pair = codeTable.find { k, v -> codedMsg.startsWith(v) } pair ? pair.key + decode(codedMsg.substring(pair.value.size()), codeTable) : decoded }
#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; 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; int *a = heap->h; while(i < heap->n) { 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; } 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; }
Produce a functionally identical C# code for the snippet given in Groovy.
import groovy.transform.* @Canonical @Sortable(includes = ['freq', 'letter']) class Node { String letter int freq Node left Node right boolean isLeaf() { left == null && right == null } } Map correspondance(Node n, Map corresp = [:], String prefix = '') { if (n.isLeaf()) { corresp[n.letter] = prefix ?: '0' } else { correspondance(n.left, corresp, prefix + '0') correspondance(n.right, corresp, prefix + '1') } return corresp } Map huffmanCode(String message) { def queue = message.toList().countBy { it } .collect { String letter, int freq -> new Node(letter, freq) } as TreeSet while(queue.size() > 1) { def (nodeLeft, nodeRight) = [queue.pollFirst(), queue.pollFirst()] queue << new Node( freq: nodeLeft.freq + nodeRight.freq, letter: nodeLeft.letter + nodeRight.letter, left: nodeLeft, right: nodeRight ) } return correspondance(queue.pollFirst()) } String encode(CharSequence msg, Map codeTable) { msg.collect { codeTable[it] }.join() } String decode(String codedMsg, Map codeTable, String decoded = '') { def pair = codeTable.find { k, v -> codedMsg.startsWith(v) } pair ? pair.key + decode(codedMsg.substring(pair.value.size()), codeTable) : decoded }
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(); } } }
Port the provided Groovy code into C++ while preserving the original functionality.
import groovy.transform.* @Canonical @Sortable(includes = ['freq', 'letter']) class Node { String letter int freq Node left Node right boolean isLeaf() { left == null && right == null } } Map correspondance(Node n, Map corresp = [:], String prefix = '') { if (n.isLeaf()) { corresp[n.letter] = prefix ?: '0' } else { correspondance(n.left, corresp, prefix + '0') correspondance(n.right, corresp, prefix + '1') } return corresp } Map huffmanCode(String message) { def queue = message.toList().countBy { it } .collect { String letter, int freq -> new Node(letter, freq) } as TreeSet while(queue.size() > 1) { def (nodeLeft, nodeRight) = [queue.pollFirst(), queue.pollFirst()] queue << new Node( freq: nodeLeft.freq + nodeRight.freq, letter: nodeLeft.letter + nodeRight.letter, left: nodeLeft, right: nodeRight ) } return correspondance(queue.pollFirst()) } String encode(CharSequence msg, Map codeTable) { msg.collect { codeTable[it] }.join() } String decode(String codedMsg, Map codeTable, String decoded = '') { def pair = codeTable.find { k, v -> codedMsg.startsWith(v) } pair ? pair.key + decode(codedMsg.substring(pair.value.size()), codeTable) : decoded }
#include <iostream> #include <queue> #include <map> #include <climits> #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() { 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; }
Change the programming language of this snippet from Groovy to Java without modifying what it does.
import groovy.transform.* @Canonical @Sortable(includes = ['freq', 'letter']) class Node { String letter int freq Node left Node right boolean isLeaf() { left == null && right == null } } Map correspondance(Node n, Map corresp = [:], String prefix = '') { if (n.isLeaf()) { corresp[n.letter] = prefix ?: '0' } else { correspondance(n.left, corresp, prefix + '0') correspondance(n.right, corresp, prefix + '1') } return corresp } Map huffmanCode(String message) { def queue = message.toList().countBy { it } .collect { String letter, int freq -> new Node(letter, freq) } as TreeSet while(queue.size() > 1) { def (nodeLeft, nodeRight) = [queue.pollFirst(), queue.pollFirst()] queue << new Node( freq: nodeLeft.freq + nodeRight.freq, letter: nodeLeft.letter + nodeRight.letter, left: nodeLeft, right: nodeRight ) } return correspondance(queue.pollFirst()) } String encode(CharSequence msg, Map codeTable) { msg.collect { codeTable[it] }.join() } String decode(String codedMsg, Map codeTable, String decoded = '') { def pair = codeTable.find { k, v -> codedMsg.startsWith(v) } pair ? pair.key + decode(codedMsg.substring(pair.value.size()), codeTable) : decoded }
import java.util.*; abstract class HuffmanTree implements Comparable<HuffmanTree> { public final int frequency; public HuffmanTree(int freq) { frequency = freq; } public int compareTo(HuffmanTree tree) { return frequency - tree.frequency; } } class HuffmanLeaf extends HuffmanTree { public final char value; public HuffmanLeaf(int freq, char val) { super(freq); value = val; } } class HuffmanNode extends HuffmanTree { public final HuffmanTree left, right; public HuffmanNode(HuffmanTree l, HuffmanTree r) { super(l.frequency + r.frequency); left = l; right = r; } } public class HuffmanCode { public static HuffmanTree buildTree(int[] charFreqs) { PriorityQueue<HuffmanTree> trees = new PriorityQueue<HuffmanTree>(); for (int i = 0; i < charFreqs.length; i++) if (charFreqs[i] > 0) trees.offer(new HuffmanLeaf(charFreqs[i], (char)i)); assert trees.size() > 0; while (trees.size() > 1) { HuffmanTree a = trees.poll(); HuffmanTree b = trees.poll(); 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; System.out.println(leaf.value + "\t" + leaf.frequency + "\t" + prefix); } else if (tree instanceof HuffmanNode) { HuffmanNode node = (HuffmanNode)tree; prefix.append('0'); printCodes(node.left, prefix); prefix.deleteCharAt(prefix.length()-1); 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"; int[] charFreqs = new int[256]; for (char c : test.toCharArray()) charFreqs[c]++; HuffmanTree tree = buildTree(charFreqs); System.out.println("SYMBOL\tWEIGHT\tHUFFMAN CODE"); printCodes(tree, new StringBuffer()); } }
Please provide an equivalent version of this Groovy code in Python.
import groovy.transform.* @Canonical @Sortable(includes = ['freq', 'letter']) class Node { String letter int freq Node left Node right boolean isLeaf() { left == null && right == null } } Map correspondance(Node n, Map corresp = [:], String prefix = '') { if (n.isLeaf()) { corresp[n.letter] = prefix ?: '0' } else { correspondance(n.left, corresp, prefix + '0') correspondance(n.right, corresp, prefix + '1') } return corresp } Map huffmanCode(String message) { def queue = message.toList().countBy { it } .collect { String letter, int freq -> new Node(letter, freq) } as TreeSet while(queue.size() > 1) { def (nodeLeft, nodeRight) = [queue.pollFirst(), queue.pollFirst()] queue << new Node( freq: nodeLeft.freq + nodeRight.freq, letter: nodeLeft.letter + nodeRight.letter, left: nodeLeft, right: nodeRight ) } return correspondance(queue.pollFirst()) } String encode(CharSequence msg, Map codeTable) { msg.collect { codeTable[it] }.join() } String decode(String codedMsg, Map codeTable, String decoded = '') { def pair = codeTable.find { k, v -> codedMsg.startsWith(v) } pair ? pair.key + decode(codedMsg.substring(pair.value.size()), codeTable) : decoded }
from heapq import heappush, heappop, heapify from collections import defaultdict def encode(symb2freq): 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 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])
Change the programming language of this snippet from Groovy to Go without modifying what it does.
import groovy.transform.* @Canonical @Sortable(includes = ['freq', 'letter']) class Node { String letter int freq Node left Node right boolean isLeaf() { left == null && right == null } } Map correspondance(Node n, Map corresp = [:], String prefix = '') { if (n.isLeaf()) { corresp[n.letter] = prefix ?: '0' } else { correspondance(n.left, corresp, prefix + '0') correspondance(n.right, corresp, prefix + '1') } return corresp } Map huffmanCode(String message) { def queue = message.toList().countBy { it } .collect { String letter, int freq -> new Node(letter, freq) } as TreeSet while(queue.size() > 1) { def (nodeLeft, nodeRight) = [queue.pollFirst(), queue.pollFirst()] queue << new Node( freq: nodeLeft.freq + nodeRight.freq, letter: nodeLeft.letter + nodeRight.letter, left: nodeLeft, right: nodeRight ) } return correspondance(queue.pollFirst()) } String encode(CharSequence msg, Map codeTable) { msg.collect { codeTable[it] }.join() } String decode(String codedMsg, Map codeTable, String decoded = '') { def pair = codeTable.find { k, v -> codedMsg.startsWith(v) } pair ? pair.key + decode(codedMsg.substring(pair.value.size()), codeTable) : decoded }
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 { a := heap.Pop(&trees).(HuffmanTree) b := heap.Pop(&trees).(HuffmanTree) 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: fmt.Printf("%c\t%d\t%s\n", i.value, i.freq, string(prefix)) case HuffmanNode: prefix = append(prefix, '0') printCodes(i.left, prefix) prefix = prefix[:len(prefix)-1] 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) for _, c := range test { symFreqs[c]++ } tree := buildTree(symFreqs) fmt.Println("SYMBOL\tWEIGHT\tHUFFMAN CODE") printCodes(tree, []byte{}) }
Convert this Haskell snippet to C and keep its semantics consistent.
import Data.List (group, insertBy, sort, sortBy) import Control.Arrow ((&&&), second) import Data.Ord (comparing) data HTree a = Leaf a | Branch (HTree a) (HTree a) deriving (Show, Eq, Ord) test :: String -> IO () test = mapM_ (\(a, b) -> putStrLn ('\'' : a : ("' : " ++ b))) . serialize . huffmanTree . freq serialize :: HTree a -> [(a, String)] serialize (Branch l r) = (second ('0' :) <$> serialize l) ++ (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) . fmap (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 = fmap (length &&& head) . group . sort main :: IO () main = test "this is an example for huffman encoding"
#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; 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; int *a = heap->h; while(i < heap->n) { 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; } 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; }
Generate an equivalent C# version of this Haskell code.
import Data.List (group, insertBy, sort, sortBy) import Control.Arrow ((&&&), second) import Data.Ord (comparing) data HTree a = Leaf a | Branch (HTree a) (HTree a) deriving (Show, Eq, Ord) test :: String -> IO () test = mapM_ (\(a, b) -> putStrLn ('\'' : a : ("' : " ++ b))) . serialize . huffmanTree . freq serialize :: HTree a -> [(a, String)] serialize (Branch l r) = (second ('0' :) <$> serialize l) ++ (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) . fmap (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 = fmap (length &&& head) . group . sort main :: IO () main = test "this is an example for huffman encoding"
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(); } } }
Convert this Haskell block to C++, preserving its control flow and logic.
import Data.List (group, insertBy, sort, sortBy) import Control.Arrow ((&&&), second) import Data.Ord (comparing) data HTree a = Leaf a | Branch (HTree a) (HTree a) deriving (Show, Eq, Ord) test :: String -> IO () test = mapM_ (\(a, b) -> putStrLn ('\'' : a : ("' : " ++ b))) . serialize . huffmanTree . freq serialize :: HTree a -> [(a, String)] serialize (Branch l r) = (second ('0' :) <$> serialize l) ++ (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) . fmap (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 = fmap (length &&& head) . group . sort main :: IO () main = test "this is an example for huffman encoding"
#include <iostream> #include <queue> #include <map> #include <climits> #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() { 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; }
Generate a Java translation of this Haskell snippet without changing its computational steps.
import Data.List (group, insertBy, sort, sortBy) import Control.Arrow ((&&&), second) import Data.Ord (comparing) data HTree a = Leaf a | Branch (HTree a) (HTree a) deriving (Show, Eq, Ord) test :: String -> IO () test = mapM_ (\(a, b) -> putStrLn ('\'' : a : ("' : " ++ b))) . serialize . huffmanTree . freq serialize :: HTree a -> [(a, String)] serialize (Branch l r) = (second ('0' :) <$> serialize l) ++ (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) . fmap (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 = fmap (length &&& head) . group . sort main :: IO () main = test "this is an example for huffman encoding"
import java.util.*; abstract class HuffmanTree implements Comparable<HuffmanTree> { public final int frequency; public HuffmanTree(int freq) { frequency = freq; } public int compareTo(HuffmanTree tree) { return frequency - tree.frequency; } } class HuffmanLeaf extends HuffmanTree { public final char value; public HuffmanLeaf(int freq, char val) { super(freq); value = val; } } class HuffmanNode extends HuffmanTree { public final HuffmanTree left, right; public HuffmanNode(HuffmanTree l, HuffmanTree r) { super(l.frequency + r.frequency); left = l; right = r; } } public class HuffmanCode { public static HuffmanTree buildTree(int[] charFreqs) { PriorityQueue<HuffmanTree> trees = new PriorityQueue<HuffmanTree>(); for (int i = 0; i < charFreqs.length; i++) if (charFreqs[i] > 0) trees.offer(new HuffmanLeaf(charFreqs[i], (char)i)); assert trees.size() > 0; while (trees.size() > 1) { HuffmanTree a = trees.poll(); HuffmanTree b = trees.poll(); 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; System.out.println(leaf.value + "\t" + leaf.frequency + "\t" + prefix); } else if (tree instanceof HuffmanNode) { HuffmanNode node = (HuffmanNode)tree; prefix.append('0'); printCodes(node.left, prefix); prefix.deleteCharAt(prefix.length()-1); 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"; int[] charFreqs = new int[256]; for (char c : test.toCharArray()) charFreqs[c]++; HuffmanTree tree = buildTree(charFreqs); System.out.println("SYMBOL\tWEIGHT\tHUFFMAN CODE"); printCodes(tree, new StringBuffer()); } }
Maintain the same structure and functionality when rewriting this code in Python.
import Data.List (group, insertBy, sort, sortBy) import Control.Arrow ((&&&), second) import Data.Ord (comparing) data HTree a = Leaf a | Branch (HTree a) (HTree a) deriving (Show, Eq, Ord) test :: String -> IO () test = mapM_ (\(a, b) -> putStrLn ('\'' : a : ("' : " ++ b))) . serialize . huffmanTree . freq serialize :: HTree a -> [(a, String)] serialize (Branch l r) = (second ('0' :) <$> serialize l) ++ (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) . fmap (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 = fmap (length &&& head) . group . sort main :: IO () main = test "this is an example for huffman encoding"
from heapq import heappush, heappop, heapify from collections import defaultdict def encode(symb2freq): 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 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])
Convert this Haskell snippet to Go and keep its semantics consistent.
import Data.List (group, insertBy, sort, sortBy) import Control.Arrow ((&&&), second) import Data.Ord (comparing) data HTree a = Leaf a | Branch (HTree a) (HTree a) deriving (Show, Eq, Ord) test :: String -> IO () test = mapM_ (\(a, b) -> putStrLn ('\'' : a : ("' : " ++ b))) . serialize . huffmanTree . freq serialize :: HTree a -> [(a, String)] serialize (Branch l r) = (second ('0' :) <$> serialize l) ++ (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) . fmap (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 = fmap (length &&& head) . group . sort main :: IO () main = test "this is an example for huffman encoding"
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 { a := heap.Pop(&trees).(HuffmanTree) b := heap.Pop(&trees).(HuffmanTree) 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: fmt.Printf("%c\t%d\t%s\n", i.value, i.freq, string(prefix)) case HuffmanNode: prefix = append(prefix, '0') printCodes(i.left, prefix) prefix = prefix[:len(prefix)-1] 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) for _, c := range test { symFreqs[c]++ } tree := buildTree(symFreqs) fmt.Println("SYMBOL\tWEIGHT\tHUFFMAN CODE") printCodes(tree, []byte{}) }
Translate the given Icon code snippet into C without altering its behavior.
record huffnode(l,r,n,c) record huffcode(c,n,b,i) procedure main() s := "this is an example for huffman encoding" Count := huffcount(s) Tree := huffTree(Count) Code := [] 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 ) 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) if \N.c then return N.c suspend "0" || huffBits(N.l) suspend "1" || huffBits(N.r) end procedure huffTree(T) local Q1,Q2,x,n1,n2 Q1 := [] every x := !T do if type(x) == "huffnode" then put(Q1,x) else runerr(205,x) Q1 := sortf(Q1,3) if *Q1 > 1 then Q2 := [] while *Q1+*\Q2 > 1 do { n1 := if Q1[1] & ( ( Q1[1].n <= Q2[1].n ) | not Q2[1] ) then get(Q1) else get(Q2) n2 := if Q1[1] & ( ( Q1[1].n <= Q2[1].n ) | not Q2[1] ) then get(Q1) else get(Q2) put( Q2, huffnode( n1, n2, n1.n + n2.n ) ) } return (\Q2 | Q1)[1] end procedure huffcount(s) local c,T T := table() every c := !s do { /T[c] := huffnode(,,0,c) T[c].n +:= 1 } return T end
#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; 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; int *a = heap->h; while(i < heap->n) { 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; } 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; }
Can you help me rewrite this code in C# instead of Icon, keeping it the same logically?
record huffnode(l,r,n,c) record huffcode(c,n,b,i) procedure main() s := "this is an example for huffman encoding" Count := huffcount(s) Tree := huffTree(Count) Code := [] 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 ) 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) if \N.c then return N.c suspend "0" || huffBits(N.l) suspend "1" || huffBits(N.r) end procedure huffTree(T) local Q1,Q2,x,n1,n2 Q1 := [] every x := !T do if type(x) == "huffnode" then put(Q1,x) else runerr(205,x) Q1 := sortf(Q1,3) if *Q1 > 1 then Q2 := [] while *Q1+*\Q2 > 1 do { n1 := if Q1[1] & ( ( Q1[1].n <= Q2[1].n ) | not Q2[1] ) then get(Q1) else get(Q2) n2 := if Q1[1] & ( ( Q1[1].n <= Q2[1].n ) | not Q2[1] ) then get(Q1) else get(Q2) put( Q2, huffnode( n1, n2, n1.n + n2.n ) ) } return (\Q2 | Q1)[1] end procedure huffcount(s) local c,T T := table() every c := !s do { /T[c] := huffnode(,,0,c) T[c].n +:= 1 } return T end
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(); } } }
Translate this program into C++ but keep the logic exactly as in Icon.
record huffnode(l,r,n,c) record huffcode(c,n,b,i) procedure main() s := "this is an example for huffman encoding" Count := huffcount(s) Tree := huffTree(Count) Code := [] 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 ) 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) if \N.c then return N.c suspend "0" || huffBits(N.l) suspend "1" || huffBits(N.r) end procedure huffTree(T) local Q1,Q2,x,n1,n2 Q1 := [] every x := !T do if type(x) == "huffnode" then put(Q1,x) else runerr(205,x) Q1 := sortf(Q1,3) if *Q1 > 1 then Q2 := [] while *Q1+*\Q2 > 1 do { n1 := if Q1[1] & ( ( Q1[1].n <= Q2[1].n ) | not Q2[1] ) then get(Q1) else get(Q2) n2 := if Q1[1] & ( ( Q1[1].n <= Q2[1].n ) | not Q2[1] ) then get(Q1) else get(Q2) put( Q2, huffnode( n1, n2, n1.n + n2.n ) ) } return (\Q2 | Q1)[1] end procedure huffcount(s) local c,T T := table() every c := !s do { /T[c] := huffnode(,,0,c) T[c].n +:= 1 } return T end
#include <iostream> #include <queue> #include <map> #include <climits> #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() { 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; }
Translate this program into Java but keep the logic exactly as in Icon.
record huffnode(l,r,n,c) record huffcode(c,n,b,i) procedure main() s := "this is an example for huffman encoding" Count := huffcount(s) Tree := huffTree(Count) Code := [] 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 ) 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) if \N.c then return N.c suspend "0" || huffBits(N.l) suspend "1" || huffBits(N.r) end procedure huffTree(T) local Q1,Q2,x,n1,n2 Q1 := [] every x := !T do if type(x) == "huffnode" then put(Q1,x) else runerr(205,x) Q1 := sortf(Q1,3) if *Q1 > 1 then Q2 := [] while *Q1+*\Q2 > 1 do { n1 := if Q1[1] & ( ( Q1[1].n <= Q2[1].n ) | not Q2[1] ) then get(Q1) else get(Q2) n2 := if Q1[1] & ( ( Q1[1].n <= Q2[1].n ) | not Q2[1] ) then get(Q1) else get(Q2) put( Q2, huffnode( n1, n2, n1.n + n2.n ) ) } return (\Q2 | Q1)[1] end procedure huffcount(s) local c,T T := table() every c := !s do { /T[c] := huffnode(,,0,c) T[c].n +:= 1 } return T end
import java.util.*; abstract class HuffmanTree implements Comparable<HuffmanTree> { public final int frequency; public HuffmanTree(int freq) { frequency = freq; } public int compareTo(HuffmanTree tree) { return frequency - tree.frequency; } } class HuffmanLeaf extends HuffmanTree { public final char value; public HuffmanLeaf(int freq, char val) { super(freq); value = val; } } class HuffmanNode extends HuffmanTree { public final HuffmanTree left, right; public HuffmanNode(HuffmanTree l, HuffmanTree r) { super(l.frequency + r.frequency); left = l; right = r; } } public class HuffmanCode { public static HuffmanTree buildTree(int[] charFreqs) { PriorityQueue<HuffmanTree> trees = new PriorityQueue<HuffmanTree>(); for (int i = 0; i < charFreqs.length; i++) if (charFreqs[i] > 0) trees.offer(new HuffmanLeaf(charFreqs[i], (char)i)); assert trees.size() > 0; while (trees.size() > 1) { HuffmanTree a = trees.poll(); HuffmanTree b = trees.poll(); 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; System.out.println(leaf.value + "\t" + leaf.frequency + "\t" + prefix); } else if (tree instanceof HuffmanNode) { HuffmanNode node = (HuffmanNode)tree; prefix.append('0'); printCodes(node.left, prefix); prefix.deleteCharAt(prefix.length()-1); 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"; int[] charFreqs = new int[256]; for (char c : test.toCharArray()) charFreqs[c]++; HuffmanTree tree = buildTree(charFreqs); System.out.println("SYMBOL\tWEIGHT\tHUFFMAN CODE"); printCodes(tree, new StringBuffer()); } }
Change the following Icon code into Python without altering its purpose.
record huffnode(l,r,n,c) record huffcode(c,n,b,i) procedure main() s := "this is an example for huffman encoding" Count := huffcount(s) Tree := huffTree(Count) Code := [] 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 ) 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) if \N.c then return N.c suspend "0" || huffBits(N.l) suspend "1" || huffBits(N.r) end procedure huffTree(T) local Q1,Q2,x,n1,n2 Q1 := [] every x := !T do if type(x) == "huffnode" then put(Q1,x) else runerr(205,x) Q1 := sortf(Q1,3) if *Q1 > 1 then Q2 := [] while *Q1+*\Q2 > 1 do { n1 := if Q1[1] & ( ( Q1[1].n <= Q2[1].n ) | not Q2[1] ) then get(Q1) else get(Q2) n2 := if Q1[1] & ( ( Q1[1].n <= Q2[1].n ) | not Q2[1] ) then get(Q1) else get(Q2) put( Q2, huffnode( n1, n2, n1.n + n2.n ) ) } return (\Q2 | Q1)[1] end procedure huffcount(s) local c,T T := table() every c := !s do { /T[c] := huffnode(,,0,c) T[c].n +:= 1 } return T end
from heapq import heappush, heappop, heapify from collections import defaultdict def encode(symb2freq): 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 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])
Port the provided Icon code into Go while preserving the original functionality.
record huffnode(l,r,n,c) record huffcode(c,n,b,i) procedure main() s := "this is an example for huffman encoding" Count := huffcount(s) Tree := huffTree(Count) Code := [] 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 ) 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) if \N.c then return N.c suspend "0" || huffBits(N.l) suspend "1" || huffBits(N.r) end procedure huffTree(T) local Q1,Q2,x,n1,n2 Q1 := [] every x := !T do if type(x) == "huffnode" then put(Q1,x) else runerr(205,x) Q1 := sortf(Q1,3) if *Q1 > 1 then Q2 := [] while *Q1+*\Q2 > 1 do { n1 := if Q1[1] & ( ( Q1[1].n <= Q2[1].n ) | not Q2[1] ) then get(Q1) else get(Q2) n2 := if Q1[1] & ( ( Q1[1].n <= Q2[1].n ) | not Q2[1] ) then get(Q1) else get(Q2) put( Q2, huffnode( n1, n2, n1.n + n2.n ) ) } return (\Q2 | Q1)[1] end procedure huffcount(s) local c,T T := table() every c := !s do { /T[c] := huffnode(,,0,c) T[c].n +:= 1 } return T end
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 { a := heap.Pop(&trees).(HuffmanTree) b := heap.Pop(&trees).(HuffmanTree) 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: fmt.Printf("%c\t%d\t%s\n", i.value, i.freq, string(prefix)) case HuffmanNode: prefix = append(prefix, '0') printCodes(i.left, prefix) prefix = prefix[:len(prefix)-1] 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) for _, c := range test { symFreqs[c]++ } tree := buildTree(symFreqs) fmt.Println("SYMBOL\tWEIGHT\tHUFFMAN CODE") printCodes(tree, []byte{}) }
Keep all operations the same but rewrite the snippet in C.
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 assert. (0<:x) *. 1=#$x assert. 1 >: L.y w=. ,&.> y assert. w -: ~.w t=. 0 {:: x hc w ((< S: 0 t) i. w) { <@(1&=)@; S: 1 {:: t )
#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; 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; int *a = heap->h; while(i < heap->n) { 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; } 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; }
Generate a C# translation of this J snippet without changing its computational steps.
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 assert. (0<:x) *. 1=#$x assert. 1 >: L.y w=. ,&.> y assert. w -: ~.w t=. 0 {:: x hc w ((< S: 0 t) i. w) { <@(1&=)@; S: 1 {:: t )
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(); } } }
Please provide an equivalent version of this J code in C++.
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 assert. (0<:x) *. 1=#$x assert. 1 >: L.y w=. ,&.> y assert. w -: ~.w t=. 0 {:: x hc w ((< S: 0 t) i. w) { <@(1&=)@; S: 1 {:: t )
#include <iostream> #include <queue> #include <map> #include <climits> #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() { 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; }
Please provide an equivalent version of this J code in Java.
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 assert. (0<:x) *. 1=#$x assert. 1 >: L.y w=. ,&.> y assert. w -: ~.w t=. 0 {:: x hc w ((< S: 0 t) i. w) { <@(1&=)@; S: 1 {:: t )
import java.util.*; abstract class HuffmanTree implements Comparable<HuffmanTree> { public final int frequency; public HuffmanTree(int freq) { frequency = freq; } public int compareTo(HuffmanTree tree) { return frequency - tree.frequency; } } class HuffmanLeaf extends HuffmanTree { public final char value; public HuffmanLeaf(int freq, char val) { super(freq); value = val; } } class HuffmanNode extends HuffmanTree { public final HuffmanTree left, right; public HuffmanNode(HuffmanTree l, HuffmanTree r) { super(l.frequency + r.frequency); left = l; right = r; } } public class HuffmanCode { public static HuffmanTree buildTree(int[] charFreqs) { PriorityQueue<HuffmanTree> trees = new PriorityQueue<HuffmanTree>(); for (int i = 0; i < charFreqs.length; i++) if (charFreqs[i] > 0) trees.offer(new HuffmanLeaf(charFreqs[i], (char)i)); assert trees.size() > 0; while (trees.size() > 1) { HuffmanTree a = trees.poll(); HuffmanTree b = trees.poll(); 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; System.out.println(leaf.value + "\t" + leaf.frequency + "\t" + prefix); } else if (tree instanceof HuffmanNode) { HuffmanNode node = (HuffmanNode)tree; prefix.append('0'); printCodes(node.left, prefix); prefix.deleteCharAt(prefix.length()-1); 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"; int[] charFreqs = new int[256]; for (char c : test.toCharArray()) charFreqs[c]++; HuffmanTree tree = buildTree(charFreqs); System.out.println("SYMBOL\tWEIGHT\tHUFFMAN CODE"); printCodes(tree, new StringBuffer()); } }
Produce a language-to-language conversion: from J to Python, same semantics.
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 assert. (0<:x) *. 1=#$x assert. 1 >: L.y w=. ,&.> y assert. w -: ~.w t=. 0 {:: x hc w ((< S: 0 t) i. w) { <@(1&=)@; S: 1 {:: t )
from heapq import heappush, heappop, heapify from collections import defaultdict def encode(symb2freq): 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 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])
Convert this J block to Go, preserving its control flow and logic.
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 assert. (0<:x) *. 1=#$x assert. 1 >: L.y w=. ,&.> y assert. w -: ~.w t=. 0 {:: x hc w ((< S: 0 t) i. w) { <@(1&=)@; S: 1 {:: t )
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 { a := heap.Pop(&trees).(HuffmanTree) b := heap.Pop(&trees).(HuffmanTree) 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: fmt.Printf("%c\t%d\t%s\n", i.value, i.freq, string(prefix)) case HuffmanNode: prefix = append(prefix, '0') printCodes(i.left, prefix) prefix = prefix[:len(prefix)-1] 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) for _, c := range test { symFreqs[c]++ } tree := buildTree(symFreqs) fmt.Println("SYMBOL\tWEIGHT\tHUFFMAN CODE") printCodes(tree, []byte{}) }
Ensure the translated C code behaves exactly like the original Julia snippet.
abstract type HuffmanTree end struct HuffmanLeaf <: HuffmanTree ch::Char freq::Int end struct HuffmanNode <: HuffmanTree freq::Int left::HuffmanTree right::HuffmanTree end function makefreqdict(s::String) d = Dict{Char, Int}() for c in s if !haskey(d, c) d[c] = 1 else d[c] += 1 end end d end function huffmantree(ftable::Dict) trees::Vector{HuffmanTree} = [HuffmanLeaf(ch, fq) for (ch, fq) in ftable] while length(trees) > 1 sort!(trees, lt = (x, y) -> x.freq < y.freq, rev = true) least = pop!(trees) nextleast = pop!(trees) push!(trees, HuffmanNode(least.freq + nextleast.freq, least, nextleast)) end trees[1] end printencoding(lf::HuffmanLeaf, code) = println(lf.ch == ' ' ? "space" : lf.ch, "\t", lf.freq, "\t", code) function printencoding(nd::HuffmanNode, code) code *= '0' printencoding(nd.left, code) code = code[1:end-1] code *= '1' printencoding(nd.right, code) code = code[1:end-1] end const msg = "this is an example for huffman encoding" println("Char\tFreq\tHuffman code") printencoding(huffmantree(makefreqdict(msg)), "")
#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; 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; int *a = heap->h; while(i < heap->n) { 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; } 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; }
Convert this Julia block to C#, preserving its control flow and logic.
abstract type HuffmanTree end struct HuffmanLeaf <: HuffmanTree ch::Char freq::Int end struct HuffmanNode <: HuffmanTree freq::Int left::HuffmanTree right::HuffmanTree end function makefreqdict(s::String) d = Dict{Char, Int}() for c in s if !haskey(d, c) d[c] = 1 else d[c] += 1 end end d end function huffmantree(ftable::Dict) trees::Vector{HuffmanTree} = [HuffmanLeaf(ch, fq) for (ch, fq) in ftable] while length(trees) > 1 sort!(trees, lt = (x, y) -> x.freq < y.freq, rev = true) least = pop!(trees) nextleast = pop!(trees) push!(trees, HuffmanNode(least.freq + nextleast.freq, least, nextleast)) end trees[1] end printencoding(lf::HuffmanLeaf, code) = println(lf.ch == ' ' ? "space" : lf.ch, "\t", lf.freq, "\t", code) function printencoding(nd::HuffmanNode, code) code *= '0' printencoding(nd.left, code) code = code[1:end-1] code *= '1' printencoding(nd.right, code) code = code[1:end-1] end const msg = "this is an example for huffman encoding" println("Char\tFreq\tHuffman code") printencoding(huffmantree(makefreqdict(msg)), "")
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(); } } }
Transform the following Julia implementation into C++, maintaining the same output and logic.
abstract type HuffmanTree end struct HuffmanLeaf <: HuffmanTree ch::Char freq::Int end struct HuffmanNode <: HuffmanTree freq::Int left::HuffmanTree right::HuffmanTree end function makefreqdict(s::String) d = Dict{Char, Int}() for c in s if !haskey(d, c) d[c] = 1 else d[c] += 1 end end d end function huffmantree(ftable::Dict) trees::Vector{HuffmanTree} = [HuffmanLeaf(ch, fq) for (ch, fq) in ftable] while length(trees) > 1 sort!(trees, lt = (x, y) -> x.freq < y.freq, rev = true) least = pop!(trees) nextleast = pop!(trees) push!(trees, HuffmanNode(least.freq + nextleast.freq, least, nextleast)) end trees[1] end printencoding(lf::HuffmanLeaf, code) = println(lf.ch == ' ' ? "space" : lf.ch, "\t", lf.freq, "\t", code) function printencoding(nd::HuffmanNode, code) code *= '0' printencoding(nd.left, code) code = code[1:end-1] code *= '1' printencoding(nd.right, code) code = code[1:end-1] end const msg = "this is an example for huffman encoding" println("Char\tFreq\tHuffman code") printencoding(huffmantree(makefreqdict(msg)), "")
#include <iostream> #include <queue> #include <map> #include <climits> #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() { 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; }
Keep all operations the same but rewrite the snippet in Java.
abstract type HuffmanTree end struct HuffmanLeaf <: HuffmanTree ch::Char freq::Int end struct HuffmanNode <: HuffmanTree freq::Int left::HuffmanTree right::HuffmanTree end function makefreqdict(s::String) d = Dict{Char, Int}() for c in s if !haskey(d, c) d[c] = 1 else d[c] += 1 end end d end function huffmantree(ftable::Dict) trees::Vector{HuffmanTree} = [HuffmanLeaf(ch, fq) for (ch, fq) in ftable] while length(trees) > 1 sort!(trees, lt = (x, y) -> x.freq < y.freq, rev = true) least = pop!(trees) nextleast = pop!(trees) push!(trees, HuffmanNode(least.freq + nextleast.freq, least, nextleast)) end trees[1] end printencoding(lf::HuffmanLeaf, code) = println(lf.ch == ' ' ? "space" : lf.ch, "\t", lf.freq, "\t", code) function printencoding(nd::HuffmanNode, code) code *= '0' printencoding(nd.left, code) code = code[1:end-1] code *= '1' printencoding(nd.right, code) code = code[1:end-1] end const msg = "this is an example for huffman encoding" println("Char\tFreq\tHuffman code") printencoding(huffmantree(makefreqdict(msg)), "")
import java.util.*; abstract class HuffmanTree implements Comparable<HuffmanTree> { public final int frequency; public HuffmanTree(int freq) { frequency = freq; } public int compareTo(HuffmanTree tree) { return frequency - tree.frequency; } } class HuffmanLeaf extends HuffmanTree { public final char value; public HuffmanLeaf(int freq, char val) { super(freq); value = val; } } class HuffmanNode extends HuffmanTree { public final HuffmanTree left, right; public HuffmanNode(HuffmanTree l, HuffmanTree r) { super(l.frequency + r.frequency); left = l; right = r; } } public class HuffmanCode { public static HuffmanTree buildTree(int[] charFreqs) { PriorityQueue<HuffmanTree> trees = new PriorityQueue<HuffmanTree>(); for (int i = 0; i < charFreqs.length; i++) if (charFreqs[i] > 0) trees.offer(new HuffmanLeaf(charFreqs[i], (char)i)); assert trees.size() > 0; while (trees.size() > 1) { HuffmanTree a = trees.poll(); HuffmanTree b = trees.poll(); 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; System.out.println(leaf.value + "\t" + leaf.frequency + "\t" + prefix); } else if (tree instanceof HuffmanNode) { HuffmanNode node = (HuffmanNode)tree; prefix.append('0'); printCodes(node.left, prefix); prefix.deleteCharAt(prefix.length()-1); 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"; int[] charFreqs = new int[256]; for (char c : test.toCharArray()) charFreqs[c]++; HuffmanTree tree = buildTree(charFreqs); System.out.println("SYMBOL\tWEIGHT\tHUFFMAN CODE"); printCodes(tree, new StringBuffer()); } }
Write the same code in Python as shown below in Julia.
abstract type HuffmanTree end struct HuffmanLeaf <: HuffmanTree ch::Char freq::Int end struct HuffmanNode <: HuffmanTree freq::Int left::HuffmanTree right::HuffmanTree end function makefreqdict(s::String) d = Dict{Char, Int}() for c in s if !haskey(d, c) d[c] = 1 else d[c] += 1 end end d end function huffmantree(ftable::Dict) trees::Vector{HuffmanTree} = [HuffmanLeaf(ch, fq) for (ch, fq) in ftable] while length(trees) > 1 sort!(trees, lt = (x, y) -> x.freq < y.freq, rev = true) least = pop!(trees) nextleast = pop!(trees) push!(trees, HuffmanNode(least.freq + nextleast.freq, least, nextleast)) end trees[1] end printencoding(lf::HuffmanLeaf, code) = println(lf.ch == ' ' ? "space" : lf.ch, "\t", lf.freq, "\t", code) function printencoding(nd::HuffmanNode, code) code *= '0' printencoding(nd.left, code) code = code[1:end-1] code *= '1' printencoding(nd.right, code) code = code[1:end-1] end const msg = "this is an example for huffman encoding" println("Char\tFreq\tHuffman code") printencoding(huffmantree(makefreqdict(msg)), "")
from heapq import heappush, heappop, heapify from collections import defaultdict def encode(symb2freq): 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 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])
Write the same algorithm in Go as shown in this Julia implementation.
abstract type HuffmanTree end struct HuffmanLeaf <: HuffmanTree ch::Char freq::Int end struct HuffmanNode <: HuffmanTree freq::Int left::HuffmanTree right::HuffmanTree end function makefreqdict(s::String) d = Dict{Char, Int}() for c in s if !haskey(d, c) d[c] = 1 else d[c] += 1 end end d end function huffmantree(ftable::Dict) trees::Vector{HuffmanTree} = [HuffmanLeaf(ch, fq) for (ch, fq) in ftable] while length(trees) > 1 sort!(trees, lt = (x, y) -> x.freq < y.freq, rev = true) least = pop!(trees) nextleast = pop!(trees) push!(trees, HuffmanNode(least.freq + nextleast.freq, least, nextleast)) end trees[1] end printencoding(lf::HuffmanLeaf, code) = println(lf.ch == ' ' ? "space" : lf.ch, "\t", lf.freq, "\t", code) function printencoding(nd::HuffmanNode, code) code *= '0' printencoding(nd.left, code) code = code[1:end-1] code *= '1' printencoding(nd.right, code) code = code[1:end-1] end const msg = "this is an example for huffman encoding" println("Char\tFreq\tHuffman code") printencoding(huffmantree(makefreqdict(msg)), "")
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 { a := heap.Pop(&trees).(HuffmanTree) b := heap.Pop(&trees).(HuffmanTree) 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: fmt.Printf("%c\t%d\t%s\n", i.value, i.freq, string(prefix)) case HuffmanNode: prefix = append(prefix, '0') printCodes(i.left, prefix) prefix = prefix[:len(prefix)-1] 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) for _, c := range test { symFreqs[c]++ } tree := buildTree(symFreqs) fmt.Println("SYMBOL\tWEIGHT\tHUFFMAN CODE") printCodes(tree, []byte{}) }
Transform the following Lua implementation into C, maintaining the same output and logic.
local build_freqtable = function (data) local freq = { } for i = 1, #data do local cur = string.sub (data, i, i) local count = freq [cur] or 0 freq [cur] = count + 1 end local nodes = { } for w, f in next, freq do nodes [#nodes + 1] = { word = w, freq = f } end table.sort (nodes, function (a, b) return a.freq > b.freq end) return nodes end local build_hufftree = function (nodes) while true do local n = #nodes local left = nodes [n] nodes [n] = nil local right = nodes [n - 1] nodes [n - 1] = nil local new = { freq = left.freq + right.freq, left = left, right = right } if n == 2 then return new end local prio = 1 while prio < #nodes and nodes [prio].freq > new.freq do prio = prio + 1 end table.insert (nodes, prio, new) end end local print_huffcodes do local rec_build_huffcodes rec_build_huffcodes = function (node, bits, acc) if node.word == nil then rec_build_huffcodes (node.left, bits .. "0", acc) rec_build_huffcodes (node.right, bits .. "1", acc) return acc else acc [#acc + 1] = { node.freq, node.word, bits } end return acc end print_huffcodes = function (root) local codes = rec_build_huffcodes (root, "", { }) table.sort (codes, function (a, b) return a [1] < b [1] end) print ("frequency\tword\thuffman code") for i = 1, #codes do print (string.format ("%9d\t‘%s’\t“%s”", table.unpack (codes [i]))) end end end local huffcode = function (data) local nodes = build_freqtable (data) local huff = build_hufftree (nodes) print_huffcodes (huff) return 0 end return huffcode "this is an example for huffman encoding"
#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; 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; int *a = heap->h; while(i < heap->n) { 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; } 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; }
Write the same code in C# as shown below in Lua.
local build_freqtable = function (data) local freq = { } for i = 1, #data do local cur = string.sub (data, i, i) local count = freq [cur] or 0 freq [cur] = count + 1 end local nodes = { } for w, f in next, freq do nodes [#nodes + 1] = { word = w, freq = f } end table.sort (nodes, function (a, b) return a.freq > b.freq end) return nodes end local build_hufftree = function (nodes) while true do local n = #nodes local left = nodes [n] nodes [n] = nil local right = nodes [n - 1] nodes [n - 1] = nil local new = { freq = left.freq + right.freq, left = left, right = right } if n == 2 then return new end local prio = 1 while prio < #nodes and nodes [prio].freq > new.freq do prio = prio + 1 end table.insert (nodes, prio, new) end end local print_huffcodes do local rec_build_huffcodes rec_build_huffcodes = function (node, bits, acc) if node.word == nil then rec_build_huffcodes (node.left, bits .. "0", acc) rec_build_huffcodes (node.right, bits .. "1", acc) return acc else acc [#acc + 1] = { node.freq, node.word, bits } end return acc end print_huffcodes = function (root) local codes = rec_build_huffcodes (root, "", { }) table.sort (codes, function (a, b) return a [1] < b [1] end) print ("frequency\tword\thuffman code") for i = 1, #codes do print (string.format ("%9d\t‘%s’\t“%s”", table.unpack (codes [i]))) end end end local huffcode = function (data) local nodes = build_freqtable (data) local huff = build_hufftree (nodes) print_huffcodes (huff) return 0 end return huffcode "this is an example for huffman encoding"
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(); } } }
Port the following code from Lua to C++ with equivalent syntax and logic.
local build_freqtable = function (data) local freq = { } for i = 1, #data do local cur = string.sub (data, i, i) local count = freq [cur] or 0 freq [cur] = count + 1 end local nodes = { } for w, f in next, freq do nodes [#nodes + 1] = { word = w, freq = f } end table.sort (nodes, function (a, b) return a.freq > b.freq end) return nodes end local build_hufftree = function (nodes) while true do local n = #nodes local left = nodes [n] nodes [n] = nil local right = nodes [n - 1] nodes [n - 1] = nil local new = { freq = left.freq + right.freq, left = left, right = right } if n == 2 then return new end local prio = 1 while prio < #nodes and nodes [prio].freq > new.freq do prio = prio + 1 end table.insert (nodes, prio, new) end end local print_huffcodes do local rec_build_huffcodes rec_build_huffcodes = function (node, bits, acc) if node.word == nil then rec_build_huffcodes (node.left, bits .. "0", acc) rec_build_huffcodes (node.right, bits .. "1", acc) return acc else acc [#acc + 1] = { node.freq, node.word, bits } end return acc end print_huffcodes = function (root) local codes = rec_build_huffcodes (root, "", { }) table.sort (codes, function (a, b) return a [1] < b [1] end) print ("frequency\tword\thuffman code") for i = 1, #codes do print (string.format ("%9d\t‘%s’\t“%s”", table.unpack (codes [i]))) end end end local huffcode = function (data) local nodes = build_freqtable (data) local huff = build_hufftree (nodes) print_huffcodes (huff) return 0 end return huffcode "this is an example for huffman encoding"
#include <iostream> #include <queue> #include <map> #include <climits> #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() { 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; }
Rewrite this program in Java while keeping its functionality equivalent to the Lua version.
local build_freqtable = function (data) local freq = { } for i = 1, #data do local cur = string.sub (data, i, i) local count = freq [cur] or 0 freq [cur] = count + 1 end local nodes = { } for w, f in next, freq do nodes [#nodes + 1] = { word = w, freq = f } end table.sort (nodes, function (a, b) return a.freq > b.freq end) return nodes end local build_hufftree = function (nodes) while true do local n = #nodes local left = nodes [n] nodes [n] = nil local right = nodes [n - 1] nodes [n - 1] = nil local new = { freq = left.freq + right.freq, left = left, right = right } if n == 2 then return new end local prio = 1 while prio < #nodes and nodes [prio].freq > new.freq do prio = prio + 1 end table.insert (nodes, prio, new) end end local print_huffcodes do local rec_build_huffcodes rec_build_huffcodes = function (node, bits, acc) if node.word == nil then rec_build_huffcodes (node.left, bits .. "0", acc) rec_build_huffcodes (node.right, bits .. "1", acc) return acc else acc [#acc + 1] = { node.freq, node.word, bits } end return acc end print_huffcodes = function (root) local codes = rec_build_huffcodes (root, "", { }) table.sort (codes, function (a, b) return a [1] < b [1] end) print ("frequency\tword\thuffman code") for i = 1, #codes do print (string.format ("%9d\t‘%s’\t“%s”", table.unpack (codes [i]))) end end end local huffcode = function (data) local nodes = build_freqtable (data) local huff = build_hufftree (nodes) print_huffcodes (huff) return 0 end return huffcode "this is an example for huffman encoding"
import java.util.*; abstract class HuffmanTree implements Comparable<HuffmanTree> { public final int frequency; public HuffmanTree(int freq) { frequency = freq; } public int compareTo(HuffmanTree tree) { return frequency - tree.frequency; } } class HuffmanLeaf extends HuffmanTree { public final char value; public HuffmanLeaf(int freq, char val) { super(freq); value = val; } } class HuffmanNode extends HuffmanTree { public final HuffmanTree left, right; public HuffmanNode(HuffmanTree l, HuffmanTree r) { super(l.frequency + r.frequency); left = l; right = r; } } public class HuffmanCode { public static HuffmanTree buildTree(int[] charFreqs) { PriorityQueue<HuffmanTree> trees = new PriorityQueue<HuffmanTree>(); for (int i = 0; i < charFreqs.length; i++) if (charFreqs[i] > 0) trees.offer(new HuffmanLeaf(charFreqs[i], (char)i)); assert trees.size() > 0; while (trees.size() > 1) { HuffmanTree a = trees.poll(); HuffmanTree b = trees.poll(); 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; System.out.println(leaf.value + "\t" + leaf.frequency + "\t" + prefix); } else if (tree instanceof HuffmanNode) { HuffmanNode node = (HuffmanNode)tree; prefix.append('0'); printCodes(node.left, prefix); prefix.deleteCharAt(prefix.length()-1); 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"; int[] charFreqs = new int[256]; for (char c : test.toCharArray()) charFreqs[c]++; HuffmanTree tree = buildTree(charFreqs); System.out.println("SYMBOL\tWEIGHT\tHUFFMAN CODE"); printCodes(tree, new StringBuffer()); } }
Write the same code in Python as shown below in Lua.
local build_freqtable = function (data) local freq = { } for i = 1, #data do local cur = string.sub (data, i, i) local count = freq [cur] or 0 freq [cur] = count + 1 end local nodes = { } for w, f in next, freq do nodes [#nodes + 1] = { word = w, freq = f } end table.sort (nodes, function (a, b) return a.freq > b.freq end) return nodes end local build_hufftree = function (nodes) while true do local n = #nodes local left = nodes [n] nodes [n] = nil local right = nodes [n - 1] nodes [n - 1] = nil local new = { freq = left.freq + right.freq, left = left, right = right } if n == 2 then return new end local prio = 1 while prio < #nodes and nodes [prio].freq > new.freq do prio = prio + 1 end table.insert (nodes, prio, new) end end local print_huffcodes do local rec_build_huffcodes rec_build_huffcodes = function (node, bits, acc) if node.word == nil then rec_build_huffcodes (node.left, bits .. "0", acc) rec_build_huffcodes (node.right, bits .. "1", acc) return acc else acc [#acc + 1] = { node.freq, node.word, bits } end return acc end print_huffcodes = function (root) local codes = rec_build_huffcodes (root, "", { }) table.sort (codes, function (a, b) return a [1] < b [1] end) print ("frequency\tword\thuffman code") for i = 1, #codes do print (string.format ("%9d\t‘%s’\t“%s”", table.unpack (codes [i]))) end end end local huffcode = function (data) local nodes = build_freqtable (data) local huff = build_hufftree (nodes) print_huffcodes (huff) return 0 end return huffcode "this is an example for huffman encoding"
from heapq import heappush, heappop, heapify from collections import defaultdict def encode(symb2freq): 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 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])
Can you help me rewrite this code in Go instead of Lua, keeping it the same logically?
local build_freqtable = function (data) local freq = { } for i = 1, #data do local cur = string.sub (data, i, i) local count = freq [cur] or 0 freq [cur] = count + 1 end local nodes = { } for w, f in next, freq do nodes [#nodes + 1] = { word = w, freq = f } end table.sort (nodes, function (a, b) return a.freq > b.freq end) return nodes end local build_hufftree = function (nodes) while true do local n = #nodes local left = nodes [n] nodes [n] = nil local right = nodes [n - 1] nodes [n - 1] = nil local new = { freq = left.freq + right.freq, left = left, right = right } if n == 2 then return new end local prio = 1 while prio < #nodes and nodes [prio].freq > new.freq do prio = prio + 1 end table.insert (nodes, prio, new) end end local print_huffcodes do local rec_build_huffcodes rec_build_huffcodes = function (node, bits, acc) if node.word == nil then rec_build_huffcodes (node.left, bits .. "0", acc) rec_build_huffcodes (node.right, bits .. "1", acc) return acc else acc [#acc + 1] = { node.freq, node.word, bits } end return acc end print_huffcodes = function (root) local codes = rec_build_huffcodes (root, "", { }) table.sort (codes, function (a, b) return a [1] < b [1] end) print ("frequency\tword\thuffman code") for i = 1, #codes do print (string.format ("%9d\t‘%s’\t“%s”", table.unpack (codes [i]))) end end end local huffcode = function (data) local nodes = build_freqtable (data) local huff = build_hufftree (nodes) print_huffcodes (huff) return 0 end return huffcode "this is an example for huffman encoding"
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 { a := heap.Pop(&trees).(HuffmanTree) b := heap.Pop(&trees).(HuffmanTree) 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: fmt.Printf("%c\t%d\t%s\n", i.value, i.freq, string(prefix)) case HuffmanNode: prefix = append(prefix, '0') printCodes(i.left, prefix) prefix = prefix[:len(prefix)-1] 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) for _, c := range test { symFreqs[c]++ } tree := buildTree(symFreqs) fmt.Println("SYMBOL\tWEIGHT\tHUFFMAN CODE") printCodes(tree, []byte{}) }
Can you help me rewrite this code in C instead of Mathematica, keeping it the same logically?
huffman[s_String] := huffman[Characters[s]]; huffman[l_List] := Module[{merge, structure, rules}, merge[k_] := Replace[k, {{a_, aC_}, {b_, bC_}, rest___} :> {{{a, b}, aC + bC}, rest}]; structure = FixedPoint[ Composition[merge, SortBy[#, Last] &], Tally[l]][[1, 1]]; rules = (# -> Flatten[Position[structure, #] - 1]) & /@ DeleteDuplicates[l]; {Flatten[l /. rules], rules}];
#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; 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; int *a = heap->h; while(i < heap->n) { 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; } 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; }
Keep all operations the same but rewrite the snippet in C#.
huffman[s_String] := huffman[Characters[s]]; huffman[l_List] := Module[{merge, structure, rules}, merge[k_] := Replace[k, {{a_, aC_}, {b_, bC_}, rest___} :> {{{a, b}, aC + bC}, rest}]; structure = FixedPoint[ Composition[merge, SortBy[#, Last] &], Tally[l]][[1, 1]]; rules = (# -> Flatten[Position[structure, #] - 1]) & /@ DeleteDuplicates[l]; {Flatten[l /. rules], rules}];
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(); } } }
Maintain the same structure and functionality when rewriting this code in C++.
huffman[s_String] := huffman[Characters[s]]; huffman[l_List] := Module[{merge, structure, rules}, merge[k_] := Replace[k, {{a_, aC_}, {b_, bC_}, rest___} :> {{{a, b}, aC + bC}, rest}]; structure = FixedPoint[ Composition[merge, SortBy[#, Last] &], Tally[l]][[1, 1]]; rules = (# -> Flatten[Position[structure, #] - 1]) & /@ DeleteDuplicates[l]; {Flatten[l /. rules], rules}];
#include <iostream> #include <queue> #include <map> #include <climits> #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() { 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; }
Generate an equivalent Java version of this Mathematica code.
huffman[s_String] := huffman[Characters[s]]; huffman[l_List] := Module[{merge, structure, rules}, merge[k_] := Replace[k, {{a_, aC_}, {b_, bC_}, rest___} :> {{{a, b}, aC + bC}, rest}]; structure = FixedPoint[ Composition[merge, SortBy[#, Last] &], Tally[l]][[1, 1]]; rules = (# -> Flatten[Position[structure, #] - 1]) & /@ DeleteDuplicates[l]; {Flatten[l /. rules], rules}];
import java.util.*; abstract class HuffmanTree implements Comparable<HuffmanTree> { public final int frequency; public HuffmanTree(int freq) { frequency = freq; } public int compareTo(HuffmanTree tree) { return frequency - tree.frequency; } } class HuffmanLeaf extends HuffmanTree { public final char value; public HuffmanLeaf(int freq, char val) { super(freq); value = val; } } class HuffmanNode extends HuffmanTree { public final HuffmanTree left, right; public HuffmanNode(HuffmanTree l, HuffmanTree r) { super(l.frequency + r.frequency); left = l; right = r; } } public class HuffmanCode { public static HuffmanTree buildTree(int[] charFreqs) { PriorityQueue<HuffmanTree> trees = new PriorityQueue<HuffmanTree>(); for (int i = 0; i < charFreqs.length; i++) if (charFreqs[i] > 0) trees.offer(new HuffmanLeaf(charFreqs[i], (char)i)); assert trees.size() > 0; while (trees.size() > 1) { HuffmanTree a = trees.poll(); HuffmanTree b = trees.poll(); 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; System.out.println(leaf.value + "\t" + leaf.frequency + "\t" + prefix); } else if (tree instanceof HuffmanNode) { HuffmanNode node = (HuffmanNode)tree; prefix.append('0'); printCodes(node.left, prefix); prefix.deleteCharAt(prefix.length()-1); 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"; int[] charFreqs = new int[256]; for (char c : test.toCharArray()) charFreqs[c]++; HuffmanTree tree = buildTree(charFreqs); System.out.println("SYMBOL\tWEIGHT\tHUFFMAN CODE"); printCodes(tree, new StringBuffer()); } }
Write the same algorithm in Python as shown in this Mathematica implementation.
huffman[s_String] := huffman[Characters[s]]; huffman[l_List] := Module[{merge, structure, rules}, merge[k_] := Replace[k, {{a_, aC_}, {b_, bC_}, rest___} :> {{{a, b}, aC + bC}, rest}]; structure = FixedPoint[ Composition[merge, SortBy[#, Last] &], Tally[l]][[1, 1]]; rules = (# -> Flatten[Position[structure, #] - 1]) & /@ DeleteDuplicates[l]; {Flatten[l /. rules], rules}];
from heapq import heappush, heappop, heapify from collections import defaultdict def encode(symb2freq): 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 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])
Change the following Mathematica code into Go without altering its purpose.
huffman[s_String] := huffman[Characters[s]]; huffman[l_List] := Module[{merge, structure, rules}, merge[k_] := Replace[k, {{a_, aC_}, {b_, bC_}, rest___} :> {{{a, b}, aC + bC}, rest}]; structure = FixedPoint[ Composition[merge, SortBy[#, Last] &], Tally[l]][[1, 1]]; rules = (# -> Flatten[Position[structure, #] - 1]) & /@ DeleteDuplicates[l]; {Flatten[l /. rules], rules}];
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 { a := heap.Pop(&trees).(HuffmanTree) b := heap.Pop(&trees).(HuffmanTree) 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: fmt.Printf("%c\t%d\t%s\n", i.value, i.freq, string(prefix)) case HuffmanNode: prefix = append(prefix, '0') printCodes(i.left, prefix) prefix = prefix[:len(prefix)-1] 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) for _, c := range test { symFreqs[c]++ } tree := buildTree(symFreqs) fmt.Println("SYMBOL\tWEIGHT\tHUFFMAN CODE") printCodes(tree, []byte{}) }
Generate an equivalent C version of this Nim code.
import tables, sequtils type CodeSymbol = range[0..1] HuffCode = seq[CodeSymbol] Node = ref object f: int parent: Node case isLeaf: bool of true: c: char else: childs: array[CodeSymbol, Node] func `<`(a: Node, b: Node): bool = a.f < b.f func `$`(hc: HuffCode): string = result = "" for symbol in hc: result &= $symbol func freeChildList(tree: seq[Node], parent: Node = nil): seq[Node] = for node in tree: if node.parent.isNil and node != parent: result.add(node) func connect(parent: Node, child: Node) = child.parent = parent parent.f += child.f for i in parent.childs.low..parent.childs.high: if parent.childs[i] == nil: parent.childs[i] = child return func generateCodes(codes: TableRef[char, HuffCode], currentNode: Node, currentCode: HuffCode = @[]) = if currentNode.isLeaf: let key = currentNode.c codes[key] = currentCode return for i in currentNode.childs.low..currentNode.childs.high: if not currentNode.childs[i].isNil: let newCode = currentCode & i generateCodes(codes, currentNode.childs[i], newCode) func buildTree(frequencies: CountTable[char]): seq[Node] = result = newSeq[Node](frequencies.len) for i in result.low..result.high: let key = toSeq(frequencies.keys)[i] result[i] = Node(f: frequencies[key], isLeaf: true, c: key) while result.freeChildList.len > 1: let currentNode = new Node result.add(currentNode) for c in currentNode.childs: currentNode.connect(min(result.freeChildList(currentNode))) if result.freeChildList.len <= 1: break when isMainModule: import algorithm, strformat const SampleString = "this is an example for huffman encoding" SampleFrequencies = SampleString.toCountTable() func `<`(code1, code2: HuffCode): bool = if code1.len == code2.len: result = false for (c1, c2) in zip(code1, code2): if c1 != c2: return c1 < c2 else: result = code1.len < code2.len let tree = buildTree(SampleFrequencies) root = tree.freeChildList[0] var huffCodes = newTable[char, HuffCode]() generateCodes(huffCodes, root) for (key, value) in sortedByIt(toSeq(huffCodes.pairs), it[1]): echo &"'{key}' → {value}"
#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; 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; int *a = heap->h; while(i < heap->n) { 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; } 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; }
Convert the following code from Nim to C#, ensuring the logic remains intact.
import tables, sequtils type CodeSymbol = range[0..1] HuffCode = seq[CodeSymbol] Node = ref object f: int parent: Node case isLeaf: bool of true: c: char else: childs: array[CodeSymbol, Node] func `<`(a: Node, b: Node): bool = a.f < b.f func `$`(hc: HuffCode): string = result = "" for symbol in hc: result &= $symbol func freeChildList(tree: seq[Node], parent: Node = nil): seq[Node] = for node in tree: if node.parent.isNil and node != parent: result.add(node) func connect(parent: Node, child: Node) = child.parent = parent parent.f += child.f for i in parent.childs.low..parent.childs.high: if parent.childs[i] == nil: parent.childs[i] = child return func generateCodes(codes: TableRef[char, HuffCode], currentNode: Node, currentCode: HuffCode = @[]) = if currentNode.isLeaf: let key = currentNode.c codes[key] = currentCode return for i in currentNode.childs.low..currentNode.childs.high: if not currentNode.childs[i].isNil: let newCode = currentCode & i generateCodes(codes, currentNode.childs[i], newCode) func buildTree(frequencies: CountTable[char]): seq[Node] = result = newSeq[Node](frequencies.len) for i in result.low..result.high: let key = toSeq(frequencies.keys)[i] result[i] = Node(f: frequencies[key], isLeaf: true, c: key) while result.freeChildList.len > 1: let currentNode = new Node result.add(currentNode) for c in currentNode.childs: currentNode.connect(min(result.freeChildList(currentNode))) if result.freeChildList.len <= 1: break when isMainModule: import algorithm, strformat const SampleString = "this is an example for huffman encoding" SampleFrequencies = SampleString.toCountTable() func `<`(code1, code2: HuffCode): bool = if code1.len == code2.len: result = false for (c1, c2) in zip(code1, code2): if c1 != c2: return c1 < c2 else: result = code1.len < code2.len let tree = buildTree(SampleFrequencies) root = tree.freeChildList[0] var huffCodes = newTable[char, HuffCode]() generateCodes(huffCodes, root) for (key, value) in sortedByIt(toSeq(huffCodes.pairs), it[1]): echo &"'{key}' → {value}"
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(); } } }
Produce a language-to-language conversion: from Nim to C++, same semantics.
import tables, sequtils type CodeSymbol = range[0..1] HuffCode = seq[CodeSymbol] Node = ref object f: int parent: Node case isLeaf: bool of true: c: char else: childs: array[CodeSymbol, Node] func `<`(a: Node, b: Node): bool = a.f < b.f func `$`(hc: HuffCode): string = result = "" for symbol in hc: result &= $symbol func freeChildList(tree: seq[Node], parent: Node = nil): seq[Node] = for node in tree: if node.parent.isNil and node != parent: result.add(node) func connect(parent: Node, child: Node) = child.parent = parent parent.f += child.f for i in parent.childs.low..parent.childs.high: if parent.childs[i] == nil: parent.childs[i] = child return func generateCodes(codes: TableRef[char, HuffCode], currentNode: Node, currentCode: HuffCode = @[]) = if currentNode.isLeaf: let key = currentNode.c codes[key] = currentCode return for i in currentNode.childs.low..currentNode.childs.high: if not currentNode.childs[i].isNil: let newCode = currentCode & i generateCodes(codes, currentNode.childs[i], newCode) func buildTree(frequencies: CountTable[char]): seq[Node] = result = newSeq[Node](frequencies.len) for i in result.low..result.high: let key = toSeq(frequencies.keys)[i] result[i] = Node(f: frequencies[key], isLeaf: true, c: key) while result.freeChildList.len > 1: let currentNode = new Node result.add(currentNode) for c in currentNode.childs: currentNode.connect(min(result.freeChildList(currentNode))) if result.freeChildList.len <= 1: break when isMainModule: import algorithm, strformat const SampleString = "this is an example for huffman encoding" SampleFrequencies = SampleString.toCountTable() func `<`(code1, code2: HuffCode): bool = if code1.len == code2.len: result = false for (c1, c2) in zip(code1, code2): if c1 != c2: return c1 < c2 else: result = code1.len < code2.len let tree = buildTree(SampleFrequencies) root = tree.freeChildList[0] var huffCodes = newTable[char, HuffCode]() generateCodes(huffCodes, root) for (key, value) in sortedByIt(toSeq(huffCodes.pairs), it[1]): echo &"'{key}' → {value}"
#include <iostream> #include <queue> #include <map> #include <climits> #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() { 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; }
Translate this program into Java but keep the logic exactly as in Nim.
import tables, sequtils type CodeSymbol = range[0..1] HuffCode = seq[CodeSymbol] Node = ref object f: int parent: Node case isLeaf: bool of true: c: char else: childs: array[CodeSymbol, Node] func `<`(a: Node, b: Node): bool = a.f < b.f func `$`(hc: HuffCode): string = result = "" for symbol in hc: result &= $symbol func freeChildList(tree: seq[Node], parent: Node = nil): seq[Node] = for node in tree: if node.parent.isNil and node != parent: result.add(node) func connect(parent: Node, child: Node) = child.parent = parent parent.f += child.f for i in parent.childs.low..parent.childs.high: if parent.childs[i] == nil: parent.childs[i] = child return func generateCodes(codes: TableRef[char, HuffCode], currentNode: Node, currentCode: HuffCode = @[]) = if currentNode.isLeaf: let key = currentNode.c codes[key] = currentCode return for i in currentNode.childs.low..currentNode.childs.high: if not currentNode.childs[i].isNil: let newCode = currentCode & i generateCodes(codes, currentNode.childs[i], newCode) func buildTree(frequencies: CountTable[char]): seq[Node] = result = newSeq[Node](frequencies.len) for i in result.low..result.high: let key = toSeq(frequencies.keys)[i] result[i] = Node(f: frequencies[key], isLeaf: true, c: key) while result.freeChildList.len > 1: let currentNode = new Node result.add(currentNode) for c in currentNode.childs: currentNode.connect(min(result.freeChildList(currentNode))) if result.freeChildList.len <= 1: break when isMainModule: import algorithm, strformat const SampleString = "this is an example for huffman encoding" SampleFrequencies = SampleString.toCountTable() func `<`(code1, code2: HuffCode): bool = if code1.len == code2.len: result = false for (c1, c2) in zip(code1, code2): if c1 != c2: return c1 < c2 else: result = code1.len < code2.len let tree = buildTree(SampleFrequencies) root = tree.freeChildList[0] var huffCodes = newTable[char, HuffCode]() generateCodes(huffCodes, root) for (key, value) in sortedByIt(toSeq(huffCodes.pairs), it[1]): echo &"'{key}' → {value}"
import java.util.*; abstract class HuffmanTree implements Comparable<HuffmanTree> { public final int frequency; public HuffmanTree(int freq) { frequency = freq; } public int compareTo(HuffmanTree tree) { return frequency - tree.frequency; } } class HuffmanLeaf extends HuffmanTree { public final char value; public HuffmanLeaf(int freq, char val) { super(freq); value = val; } } class HuffmanNode extends HuffmanTree { public final HuffmanTree left, right; public HuffmanNode(HuffmanTree l, HuffmanTree r) { super(l.frequency + r.frequency); left = l; right = r; } } public class HuffmanCode { public static HuffmanTree buildTree(int[] charFreqs) { PriorityQueue<HuffmanTree> trees = new PriorityQueue<HuffmanTree>(); for (int i = 0; i < charFreqs.length; i++) if (charFreqs[i] > 0) trees.offer(new HuffmanLeaf(charFreqs[i], (char)i)); assert trees.size() > 0; while (trees.size() > 1) { HuffmanTree a = trees.poll(); HuffmanTree b = trees.poll(); 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; System.out.println(leaf.value + "\t" + leaf.frequency + "\t" + prefix); } else if (tree instanceof HuffmanNode) { HuffmanNode node = (HuffmanNode)tree; prefix.append('0'); printCodes(node.left, prefix); prefix.deleteCharAt(prefix.length()-1); 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"; int[] charFreqs = new int[256]; for (char c : test.toCharArray()) charFreqs[c]++; HuffmanTree tree = buildTree(charFreqs); System.out.println("SYMBOL\tWEIGHT\tHUFFMAN CODE"); printCodes(tree, new StringBuffer()); } }
Generate a Python translation of this Nim snippet without changing its computational steps.
import tables, sequtils type CodeSymbol = range[0..1] HuffCode = seq[CodeSymbol] Node = ref object f: int parent: Node case isLeaf: bool of true: c: char else: childs: array[CodeSymbol, Node] func `<`(a: Node, b: Node): bool = a.f < b.f func `$`(hc: HuffCode): string = result = "" for symbol in hc: result &= $symbol func freeChildList(tree: seq[Node], parent: Node = nil): seq[Node] = for node in tree: if node.parent.isNil and node != parent: result.add(node) func connect(parent: Node, child: Node) = child.parent = parent parent.f += child.f for i in parent.childs.low..parent.childs.high: if parent.childs[i] == nil: parent.childs[i] = child return func generateCodes(codes: TableRef[char, HuffCode], currentNode: Node, currentCode: HuffCode = @[]) = if currentNode.isLeaf: let key = currentNode.c codes[key] = currentCode return for i in currentNode.childs.low..currentNode.childs.high: if not currentNode.childs[i].isNil: let newCode = currentCode & i generateCodes(codes, currentNode.childs[i], newCode) func buildTree(frequencies: CountTable[char]): seq[Node] = result = newSeq[Node](frequencies.len) for i in result.low..result.high: let key = toSeq(frequencies.keys)[i] result[i] = Node(f: frequencies[key], isLeaf: true, c: key) while result.freeChildList.len > 1: let currentNode = new Node result.add(currentNode) for c in currentNode.childs: currentNode.connect(min(result.freeChildList(currentNode))) if result.freeChildList.len <= 1: break when isMainModule: import algorithm, strformat const SampleString = "this is an example for huffman encoding" SampleFrequencies = SampleString.toCountTable() func `<`(code1, code2: HuffCode): bool = if code1.len == code2.len: result = false for (c1, c2) in zip(code1, code2): if c1 != c2: return c1 < c2 else: result = code1.len < code2.len let tree = buildTree(SampleFrequencies) root = tree.freeChildList[0] var huffCodes = newTable[char, HuffCode]() generateCodes(huffCodes, root) for (key, value) in sortedByIt(toSeq(huffCodes.pairs), it[1]): echo &"'{key}' → {value}"
from heapq import heappush, heappop, heapify from collections import defaultdict def encode(symb2freq): 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 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])
Preserve the algorithm and functionality while converting the code from Nim to Go.
import tables, sequtils type CodeSymbol = range[0..1] HuffCode = seq[CodeSymbol] Node = ref object f: int parent: Node case isLeaf: bool of true: c: char else: childs: array[CodeSymbol, Node] func `<`(a: Node, b: Node): bool = a.f < b.f func `$`(hc: HuffCode): string = result = "" for symbol in hc: result &= $symbol func freeChildList(tree: seq[Node], parent: Node = nil): seq[Node] = for node in tree: if node.parent.isNil and node != parent: result.add(node) func connect(parent: Node, child: Node) = child.parent = parent parent.f += child.f for i in parent.childs.low..parent.childs.high: if parent.childs[i] == nil: parent.childs[i] = child return func generateCodes(codes: TableRef[char, HuffCode], currentNode: Node, currentCode: HuffCode = @[]) = if currentNode.isLeaf: let key = currentNode.c codes[key] = currentCode return for i in currentNode.childs.low..currentNode.childs.high: if not currentNode.childs[i].isNil: let newCode = currentCode & i generateCodes(codes, currentNode.childs[i], newCode) func buildTree(frequencies: CountTable[char]): seq[Node] = result = newSeq[Node](frequencies.len) for i in result.low..result.high: let key = toSeq(frequencies.keys)[i] result[i] = Node(f: frequencies[key], isLeaf: true, c: key) while result.freeChildList.len > 1: let currentNode = new Node result.add(currentNode) for c in currentNode.childs: currentNode.connect(min(result.freeChildList(currentNode))) if result.freeChildList.len <= 1: break when isMainModule: import algorithm, strformat const SampleString = "this is an example for huffman encoding" SampleFrequencies = SampleString.toCountTable() func `<`(code1, code2: HuffCode): bool = if code1.len == code2.len: result = false for (c1, c2) in zip(code1, code2): if c1 != c2: return c1 < c2 else: result = code1.len < code2.len let tree = buildTree(SampleFrequencies) root = tree.freeChildList[0] var huffCodes = newTable[char, HuffCode]() generateCodes(huffCodes, root) for (key, value) in sortedByIt(toSeq(huffCodes.pairs), it[1]): echo &"'{key}' → {value}"
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 { a := heap.Pop(&trees).(HuffmanTree) b := heap.Pop(&trees).(HuffmanTree) 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: fmt.Printf("%c\t%d\t%s\n", i.value, i.freq, string(prefix)) case HuffmanNode: prefix = append(prefix, '0') printCodes(i.left, prefix) prefix = prefix[:len(prefix)-1] 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) for _, c := range test { symFreqs[c]++ } tree := buildTree(symFreqs) fmt.Println("SYMBOL\tWEIGHT\tHUFFMAN CODE") printCodes(tree, []byte{}) }
Rewrite the snippet below in C so it works the same as the original OCaml code.
type 'a huffman_tree = | Leaf of 'a | Node of 'a huffman_tree * 'a huffman_tree module HSet = Set.Make (struct type t = int * char huffman_tree let compare = compare end);; let build_tree charFreqs = let leaves = HSet.of_list (List.map (fun (c,f) -> (f, Leaf c)) charFreqs) in let rec aux trees = let f1, a = HSet.min_elt trees in let trees' = HSet.remove (f1,a) trees in if HSet.is_empty trees' then a else let f2, b = HSet.min_elt trees' in let trees'' = HSet.remove (f2,b) trees' in let trees''' = HSet.add (f1 + f2, Node (a, b)) trees'' in aux trees''' in aux leaves let rec print_tree code = function | Leaf c -> Printf.printf "%c\t%s\n" c (String.concat "" (List.rev code)); | Node (l, r) -> print_tree ("0"::code) l; print_tree ("1"::code) r let () = let str = "this is an example for huffman encoding" in let charFreqs = Hashtbl.create 42 in String.iter (fun c -> let old = try Hashtbl.find charFreqs c with Not_found -> 0 in Hashtbl.replace charFreqs c (old+1) ) str; let charFreqs = Hashtbl.fold (fun c f acc -> (c,f)::acc) charFreqs [] in let tree = build_tree charFreqs in print_string "Symbol\tHuffman code\n"; print_tree [] tree
#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; 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; int *a = heap->h; while(i < heap->n) { 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; } 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; }
Convert this OCaml block to C#, preserving its control flow and logic.
type 'a huffman_tree = | Leaf of 'a | Node of 'a huffman_tree * 'a huffman_tree module HSet = Set.Make (struct type t = int * char huffman_tree let compare = compare end);; let build_tree charFreqs = let leaves = HSet.of_list (List.map (fun (c,f) -> (f, Leaf c)) charFreqs) in let rec aux trees = let f1, a = HSet.min_elt trees in let trees' = HSet.remove (f1,a) trees in if HSet.is_empty trees' then a else let f2, b = HSet.min_elt trees' in let trees'' = HSet.remove (f2,b) trees' in let trees''' = HSet.add (f1 + f2, Node (a, b)) trees'' in aux trees''' in aux leaves let rec print_tree code = function | Leaf c -> Printf.printf "%c\t%s\n" c (String.concat "" (List.rev code)); | Node (l, r) -> print_tree ("0"::code) l; print_tree ("1"::code) r let () = let str = "this is an example for huffman encoding" in let charFreqs = Hashtbl.create 42 in String.iter (fun c -> let old = try Hashtbl.find charFreqs c with Not_found -> 0 in Hashtbl.replace charFreqs c (old+1) ) str; let charFreqs = Hashtbl.fold (fun c f acc -> (c,f)::acc) charFreqs [] in let tree = build_tree charFreqs in print_string "Symbol\tHuffman code\n"; print_tree [] tree
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(); } } }
Translate this program into Java but keep the logic exactly as in OCaml.
type 'a huffman_tree = | Leaf of 'a | Node of 'a huffman_tree * 'a huffman_tree module HSet = Set.Make (struct type t = int * char huffman_tree let compare = compare end);; let build_tree charFreqs = let leaves = HSet.of_list (List.map (fun (c,f) -> (f, Leaf c)) charFreqs) in let rec aux trees = let f1, a = HSet.min_elt trees in let trees' = HSet.remove (f1,a) trees in if HSet.is_empty trees' then a else let f2, b = HSet.min_elt trees' in let trees'' = HSet.remove (f2,b) trees' in let trees''' = HSet.add (f1 + f2, Node (a, b)) trees'' in aux trees''' in aux leaves let rec print_tree code = function | Leaf c -> Printf.printf "%c\t%s\n" c (String.concat "" (List.rev code)); | Node (l, r) -> print_tree ("0"::code) l; print_tree ("1"::code) r let () = let str = "this is an example for huffman encoding" in let charFreqs = Hashtbl.create 42 in String.iter (fun c -> let old = try Hashtbl.find charFreqs c with Not_found -> 0 in Hashtbl.replace charFreqs c (old+1) ) str; let charFreqs = Hashtbl.fold (fun c f acc -> (c,f)::acc) charFreqs [] in let tree = build_tree charFreqs in print_string "Symbol\tHuffman code\n"; print_tree [] tree
import java.util.*; abstract class HuffmanTree implements Comparable<HuffmanTree> { public final int frequency; public HuffmanTree(int freq) { frequency = freq; } public int compareTo(HuffmanTree tree) { return frequency - tree.frequency; } } class HuffmanLeaf extends HuffmanTree { public final char value; public HuffmanLeaf(int freq, char val) { super(freq); value = val; } } class HuffmanNode extends HuffmanTree { public final HuffmanTree left, right; public HuffmanNode(HuffmanTree l, HuffmanTree r) { super(l.frequency + r.frequency); left = l; right = r; } } public class HuffmanCode { public static HuffmanTree buildTree(int[] charFreqs) { PriorityQueue<HuffmanTree> trees = new PriorityQueue<HuffmanTree>(); for (int i = 0; i < charFreqs.length; i++) if (charFreqs[i] > 0) trees.offer(new HuffmanLeaf(charFreqs[i], (char)i)); assert trees.size() > 0; while (trees.size() > 1) { HuffmanTree a = trees.poll(); HuffmanTree b = trees.poll(); 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; System.out.println(leaf.value + "\t" + leaf.frequency + "\t" + prefix); } else if (tree instanceof HuffmanNode) { HuffmanNode node = (HuffmanNode)tree; prefix.append('0'); printCodes(node.left, prefix); prefix.deleteCharAt(prefix.length()-1); 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"; int[] charFreqs = new int[256]; for (char c : test.toCharArray()) charFreqs[c]++; HuffmanTree tree = buildTree(charFreqs); System.out.println("SYMBOL\tWEIGHT\tHUFFMAN CODE"); printCodes(tree, new StringBuffer()); } }
Produce a functionally identical Python code for the snippet given in OCaml.
type 'a huffman_tree = | Leaf of 'a | Node of 'a huffman_tree * 'a huffman_tree module HSet = Set.Make (struct type t = int * char huffman_tree let compare = compare end);; let build_tree charFreqs = let leaves = HSet.of_list (List.map (fun (c,f) -> (f, Leaf c)) charFreqs) in let rec aux trees = let f1, a = HSet.min_elt trees in let trees' = HSet.remove (f1,a) trees in if HSet.is_empty trees' then a else let f2, b = HSet.min_elt trees' in let trees'' = HSet.remove (f2,b) trees' in let trees''' = HSet.add (f1 + f2, Node (a, b)) trees'' in aux trees''' in aux leaves let rec print_tree code = function | Leaf c -> Printf.printf "%c\t%s\n" c (String.concat "" (List.rev code)); | Node (l, r) -> print_tree ("0"::code) l; print_tree ("1"::code) r let () = let str = "this is an example for huffman encoding" in let charFreqs = Hashtbl.create 42 in String.iter (fun c -> let old = try Hashtbl.find charFreqs c with Not_found -> 0 in Hashtbl.replace charFreqs c (old+1) ) str; let charFreqs = Hashtbl.fold (fun c f acc -> (c,f)::acc) charFreqs [] in let tree = build_tree charFreqs in print_string "Symbol\tHuffman code\n"; print_tree [] tree
from heapq import heappush, heappop, heapify from collections import defaultdict def encode(symb2freq): 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 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])
Transform the following OCaml implementation into Go, maintaining the same output and logic.
type 'a huffman_tree = | Leaf of 'a | Node of 'a huffman_tree * 'a huffman_tree module HSet = Set.Make (struct type t = int * char huffman_tree let compare = compare end);; let build_tree charFreqs = let leaves = HSet.of_list (List.map (fun (c,f) -> (f, Leaf c)) charFreqs) in let rec aux trees = let f1, a = HSet.min_elt trees in let trees' = HSet.remove (f1,a) trees in if HSet.is_empty trees' then a else let f2, b = HSet.min_elt trees' in let trees'' = HSet.remove (f2,b) trees' in let trees''' = HSet.add (f1 + f2, Node (a, b)) trees'' in aux trees''' in aux leaves let rec print_tree code = function | Leaf c -> Printf.printf "%c\t%s\n" c (String.concat "" (List.rev code)); | Node (l, r) -> print_tree ("0"::code) l; print_tree ("1"::code) r let () = let str = "this is an example for huffman encoding" in let charFreqs = Hashtbl.create 42 in String.iter (fun c -> let old = try Hashtbl.find charFreqs c with Not_found -> 0 in Hashtbl.replace charFreqs c (old+1) ) str; let charFreqs = Hashtbl.fold (fun c f acc -> (c,f)::acc) charFreqs [] in let tree = build_tree charFreqs in print_string "Symbol\tHuffman code\n"; print_tree [] tree
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 { a := heap.Pop(&trees).(HuffmanTree) b := heap.Pop(&trees).(HuffmanTree) 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: fmt.Printf("%c\t%d\t%s\n", i.value, i.freq, string(prefix)) case HuffmanNode: prefix = append(prefix, '0') printCodes(i.left, prefix) prefix = prefix[:len(prefix)-1] 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) for _, c := range test { symFreqs[c]++ } tree := buildTree(symFreqs) fmt.Println("SYMBOL\tWEIGHT\tHUFFMAN CODE") printCodes(tree, []byte{}) }
Produce a functionally identical C code for the snippet given in Perl.
use 5.10.0; use strict; sub walk { my ($node, $code, $h, $rev_h) = @_; my $c = $node->[0]; if (ref $c) { walk($c->[$_], $code.$_, $h, $rev_h) for 0,1 } else { $h->{$c} = $code; $rev_h->{$code} = $c } $h, $rev_h } sub mktree { my (%freq, @nodes); $freq{$_}++ for split '', shift; @nodes = map([$_, $freq{$_}], keys %freq); do { @nodes = sort {$a->[1] <=> $b->[1]} @nodes; my ($x, $y) = splice @nodes, 0, 2; push @nodes, [[$x, $y], $x->[1] + $y->[1]] } while (@nodes > 1); walk($nodes[0], '', {}, {}) } sub encode { my ($str, $dict) = @_; join '', map $dict->{$_}//die("bad char $_"), split '', $str } sub decode { my ($str, $dict) = @_; my ($seg, @out) = (""); for (split '', $str) { $seg .= $_; my $x = $dict->{$seg} // next; push @out, $x; $seg = ''; } die "bad code" if length($seg); join '', @out } my $txt = 'this is an example for huffman encoding'; my ($h, $rev_h) = mktree($txt); for (keys %$h) { print "'$_': $h->{$_}\n" } my $enc = encode($txt, $h); print "$enc\n"; print decode($enc, $rev_h), "\n";
#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; 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; int *a = heap->h; while(i < heap->n) { 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; } 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; }
Generate a C# translation of this Perl snippet without changing its computational steps.
use 5.10.0; use strict; sub walk { my ($node, $code, $h, $rev_h) = @_; my $c = $node->[0]; if (ref $c) { walk($c->[$_], $code.$_, $h, $rev_h) for 0,1 } else { $h->{$c} = $code; $rev_h->{$code} = $c } $h, $rev_h } sub mktree { my (%freq, @nodes); $freq{$_}++ for split '', shift; @nodes = map([$_, $freq{$_}], keys %freq); do { @nodes = sort {$a->[1] <=> $b->[1]} @nodes; my ($x, $y) = splice @nodes, 0, 2; push @nodes, [[$x, $y], $x->[1] + $y->[1]] } while (@nodes > 1); walk($nodes[0], '', {}, {}) } sub encode { my ($str, $dict) = @_; join '', map $dict->{$_}//die("bad char $_"), split '', $str } sub decode { my ($str, $dict) = @_; my ($seg, @out) = (""); for (split '', $str) { $seg .= $_; my $x = $dict->{$seg} // next; push @out, $x; $seg = ''; } die "bad code" if length($seg); join '', @out } my $txt = 'this is an example for huffman encoding'; my ($h, $rev_h) = mktree($txt); for (keys %$h) { print "'$_': $h->{$_}\n" } my $enc = encode($txt, $h); print "$enc\n"; print decode($enc, $rev_h), "\n";
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(); } } }
Please provide an equivalent version of this Perl code in C++.
use 5.10.0; use strict; sub walk { my ($node, $code, $h, $rev_h) = @_; my $c = $node->[0]; if (ref $c) { walk($c->[$_], $code.$_, $h, $rev_h) for 0,1 } else { $h->{$c} = $code; $rev_h->{$code} = $c } $h, $rev_h } sub mktree { my (%freq, @nodes); $freq{$_}++ for split '', shift; @nodes = map([$_, $freq{$_}], keys %freq); do { @nodes = sort {$a->[1] <=> $b->[1]} @nodes; my ($x, $y) = splice @nodes, 0, 2; push @nodes, [[$x, $y], $x->[1] + $y->[1]] } while (@nodes > 1); walk($nodes[0], '', {}, {}) } sub encode { my ($str, $dict) = @_; join '', map $dict->{$_}//die("bad char $_"), split '', $str } sub decode { my ($str, $dict) = @_; my ($seg, @out) = (""); for (split '', $str) { $seg .= $_; my $x = $dict->{$seg} // next; push @out, $x; $seg = ''; } die "bad code" if length($seg); join '', @out } my $txt = 'this is an example for huffman encoding'; my ($h, $rev_h) = mktree($txt); for (keys %$h) { print "'$_': $h->{$_}\n" } my $enc = encode($txt, $h); print "$enc\n"; print decode($enc, $rev_h), "\n";
#include <iostream> #include <queue> #include <map> #include <climits> #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() { 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; }