Instruction
stringlengths
45
106
input_code
stringlengths
1
13.7k
output_code
stringlengths
1
13.7k
Translate this program into Java but keep the logic exactly as 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";
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()); } }
Preserve the algorithm and functionality while converting the code from Perl to Python.
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";
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 Perl code into Go without altering its purpose.
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";
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{}) }
Write the same algorithm in C as shown in this PowerShell implementation.
function Get-HuffmanEncodingTable ( $String ) { $ID = 0 $Nodes = [char[]]$String | Group-Object | ForEach { $ID++; $_ } | Select @{ Label = 'Symbol' ; Expression = { $_.Name } }, @{ Label = 'Count' ; Expression = { $_.Count } }, @{ Label = 'ID' ; Expression = { $ID } }, @{ Label = 'Parent' ; Expression = { 0 } }, @{ Label = 'Code' ; Expression = { '' } } ForEach ( $Branch in 2..($Nodes.Count) ) { $LowNodes = $Nodes | Where Parent -eq 0 | Sort Count | Select -First 2 $ID++ $Nodes += '' | Select @{ Label = 'Symbol' ; Expression = { '' } }, @{ Label = 'Count' ; Expression = { $LowNodes[0].Count + $LowNodes[1].Count } }, @{ Label = 'ID' ; Expression = { $ID } }, @{ Label = 'Parent' ; Expression = { 0 } }, @{ Label = 'Code' ; Expression = { '' } } $LowNodes[0].Parent = $ID $LowNodes[1].Parent = $ID $LowNodes[0].Code = '0' $LowNodes[1].Code = '1' } ForEach ( $Node in $Nodes[($Nodes.Count-2)..0] ) { $Node.Code = ( $Nodes | Where ID -eq $Node.Parent ).Code + $Node.Code } $EncodingTable = $Nodes | Where { $_.Symbol } | Select Symbol, Code | Sort Symbol return $EncodingTable } $String = "this is an example for huffman encoding" $HuffmanEncodingTable = Get-HuffmanEncodingTable $String $HuffmanEncodingTable | Format-Table -AutoSize $EncodedString = $String ForEach ( $Node in $HuffmanEncodingTable ) { $EncodedString = $EncodedString.Replace( $Node.Symbol, $Node.Code ) } $EncodedString
#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 PowerShell to C# with equivalent syntax and logic.
function Get-HuffmanEncodingTable ( $String ) { $ID = 0 $Nodes = [char[]]$String | Group-Object | ForEach { $ID++; $_ } | Select @{ Label = 'Symbol' ; Expression = { $_.Name } }, @{ Label = 'Count' ; Expression = { $_.Count } }, @{ Label = 'ID' ; Expression = { $ID } }, @{ Label = 'Parent' ; Expression = { 0 } }, @{ Label = 'Code' ; Expression = { '' } } ForEach ( $Branch in 2..($Nodes.Count) ) { $LowNodes = $Nodes | Where Parent -eq 0 | Sort Count | Select -First 2 $ID++ $Nodes += '' | Select @{ Label = 'Symbol' ; Expression = { '' } }, @{ Label = 'Count' ; Expression = { $LowNodes[0].Count + $LowNodes[1].Count } }, @{ Label = 'ID' ; Expression = { $ID } }, @{ Label = 'Parent' ; Expression = { 0 } }, @{ Label = 'Code' ; Expression = { '' } } $LowNodes[0].Parent = $ID $LowNodes[1].Parent = $ID $LowNodes[0].Code = '0' $LowNodes[1].Code = '1' } ForEach ( $Node in $Nodes[($Nodes.Count-2)..0] ) { $Node.Code = ( $Nodes | Where ID -eq $Node.Parent ).Code + $Node.Code } $EncodingTable = $Nodes | Where { $_.Symbol } | Select Symbol, Code | Sort Symbol return $EncodingTable } $String = "this is an example for huffman encoding" $HuffmanEncodingTable = Get-HuffmanEncodingTable $String $HuffmanEncodingTable | Format-Table -AutoSize $EncodedString = $String ForEach ( $Node in $HuffmanEncodingTable ) { $EncodedString = $EncodedString.Replace( $Node.Symbol, $Node.Code ) } $EncodedString
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(); } } }
Keep all operations the same but rewrite the snippet in C++.
function Get-HuffmanEncodingTable ( $String ) { $ID = 0 $Nodes = [char[]]$String | Group-Object | ForEach { $ID++; $_ } | Select @{ Label = 'Symbol' ; Expression = { $_.Name } }, @{ Label = 'Count' ; Expression = { $_.Count } }, @{ Label = 'ID' ; Expression = { $ID } }, @{ Label = 'Parent' ; Expression = { 0 } }, @{ Label = 'Code' ; Expression = { '' } } ForEach ( $Branch in 2..($Nodes.Count) ) { $LowNodes = $Nodes | Where Parent -eq 0 | Sort Count | Select -First 2 $ID++ $Nodes += '' | Select @{ Label = 'Symbol' ; Expression = { '' } }, @{ Label = 'Count' ; Expression = { $LowNodes[0].Count + $LowNodes[1].Count } }, @{ Label = 'ID' ; Expression = { $ID } }, @{ Label = 'Parent' ; Expression = { 0 } }, @{ Label = 'Code' ; Expression = { '' } } $LowNodes[0].Parent = $ID $LowNodes[1].Parent = $ID $LowNodes[0].Code = '0' $LowNodes[1].Code = '1' } ForEach ( $Node in $Nodes[($Nodes.Count-2)..0] ) { $Node.Code = ( $Nodes | Where ID -eq $Node.Parent ).Code + $Node.Code } $EncodingTable = $Nodes | Where { $_.Symbol } | Select Symbol, Code | Sort Symbol return $EncodingTable } $String = "this is an example for huffman encoding" $HuffmanEncodingTable = Get-HuffmanEncodingTable $String $HuffmanEncodingTable | Format-Table -AutoSize $EncodedString = $String ForEach ( $Node in $HuffmanEncodingTable ) { $EncodedString = $EncodedString.Replace( $Node.Symbol, $Node.Code ) } $EncodedString
#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 the snippet below in Java so it works the same as the original PowerShell code.
function Get-HuffmanEncodingTable ( $String ) { $ID = 0 $Nodes = [char[]]$String | Group-Object | ForEach { $ID++; $_ } | Select @{ Label = 'Symbol' ; Expression = { $_.Name } }, @{ Label = 'Count' ; Expression = { $_.Count } }, @{ Label = 'ID' ; Expression = { $ID } }, @{ Label = 'Parent' ; Expression = { 0 } }, @{ Label = 'Code' ; Expression = { '' } } ForEach ( $Branch in 2..($Nodes.Count) ) { $LowNodes = $Nodes | Where Parent -eq 0 | Sort Count | Select -First 2 $ID++ $Nodes += '' | Select @{ Label = 'Symbol' ; Expression = { '' } }, @{ Label = 'Count' ; Expression = { $LowNodes[0].Count + $LowNodes[1].Count } }, @{ Label = 'ID' ; Expression = { $ID } }, @{ Label = 'Parent' ; Expression = { 0 } }, @{ Label = 'Code' ; Expression = { '' } } $LowNodes[0].Parent = $ID $LowNodes[1].Parent = $ID $LowNodes[0].Code = '0' $LowNodes[1].Code = '1' } ForEach ( $Node in $Nodes[($Nodes.Count-2)..0] ) { $Node.Code = ( $Nodes | Where ID -eq $Node.Parent ).Code + $Node.Code } $EncodingTable = $Nodes | Where { $_.Symbol } | Select Symbol, Code | Sort Symbol return $EncodingTable } $String = "this is an example for huffman encoding" $HuffmanEncodingTable = Get-HuffmanEncodingTable $String $HuffmanEncodingTable | Format-Table -AutoSize $EncodedString = $String ForEach ( $Node in $HuffmanEncodingTable ) { $EncodedString = $EncodedString.Replace( $Node.Symbol, $Node.Code ) } $EncodedString
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 PowerShell.
function Get-HuffmanEncodingTable ( $String ) { $ID = 0 $Nodes = [char[]]$String | Group-Object | ForEach { $ID++; $_ } | Select @{ Label = 'Symbol' ; Expression = { $_.Name } }, @{ Label = 'Count' ; Expression = { $_.Count } }, @{ Label = 'ID' ; Expression = { $ID } }, @{ Label = 'Parent' ; Expression = { 0 } }, @{ Label = 'Code' ; Expression = { '' } } ForEach ( $Branch in 2..($Nodes.Count) ) { $LowNodes = $Nodes | Where Parent -eq 0 | Sort Count | Select -First 2 $ID++ $Nodes += '' | Select @{ Label = 'Symbol' ; Expression = { '' } }, @{ Label = 'Count' ; Expression = { $LowNodes[0].Count + $LowNodes[1].Count } }, @{ Label = 'ID' ; Expression = { $ID } }, @{ Label = 'Parent' ; Expression = { 0 } }, @{ Label = 'Code' ; Expression = { '' } } $LowNodes[0].Parent = $ID $LowNodes[1].Parent = $ID $LowNodes[0].Code = '0' $LowNodes[1].Code = '1' } ForEach ( $Node in $Nodes[($Nodes.Count-2)..0] ) { $Node.Code = ( $Nodes | Where ID -eq $Node.Parent ).Code + $Node.Code } $EncodingTable = $Nodes | Where { $_.Symbol } | Select Symbol, Code | Sort Symbol return $EncodingTable } $String = "this is an example for huffman encoding" $HuffmanEncodingTable = Get-HuffmanEncodingTable $String $HuffmanEncodingTable | Format-Table -AutoSize $EncodedString = $String ForEach ( $Node in $HuffmanEncodingTable ) { $EncodedString = $EncodedString.Replace( $Node.Symbol, $Node.Code ) } $EncodedString
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 PowerShell code into Go without altering its purpose.
function Get-HuffmanEncodingTable ( $String ) { $ID = 0 $Nodes = [char[]]$String | Group-Object | ForEach { $ID++; $_ } | Select @{ Label = 'Symbol' ; Expression = { $_.Name } }, @{ Label = 'Count' ; Expression = { $_.Count } }, @{ Label = 'ID' ; Expression = { $ID } }, @{ Label = 'Parent' ; Expression = { 0 } }, @{ Label = 'Code' ; Expression = { '' } } ForEach ( $Branch in 2..($Nodes.Count) ) { $LowNodes = $Nodes | Where Parent -eq 0 | Sort Count | Select -First 2 $ID++ $Nodes += '' | Select @{ Label = 'Symbol' ; Expression = { '' } }, @{ Label = 'Count' ; Expression = { $LowNodes[0].Count + $LowNodes[1].Count } }, @{ Label = 'ID' ; Expression = { $ID } }, @{ Label = 'Parent' ; Expression = { 0 } }, @{ Label = 'Code' ; Expression = { '' } } $LowNodes[0].Parent = $ID $LowNodes[1].Parent = $ID $LowNodes[0].Code = '0' $LowNodes[1].Code = '1' } ForEach ( $Node in $Nodes[($Nodes.Count-2)..0] ) { $Node.Code = ( $Nodes | Where ID -eq $Node.Parent ).Code + $Node.Code } $EncodingTable = $Nodes | Where { $_.Symbol } | Select Symbol, Code | Sort Symbol return $EncodingTable } $String = "this is an example for huffman encoding" $HuffmanEncodingTable = Get-HuffmanEncodingTable $String $HuffmanEncodingTable | Format-Table -AutoSize $EncodedString = $String ForEach ( $Node in $HuffmanEncodingTable ) { $EncodedString = $EncodedString.Replace( $Node.Symbol, $Node.Code ) } $EncodedString
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 Racket code snippet into C without altering its behavior.
#lang racket (require data/heap data/bit-vector) (struct node (freq) #:transparent) (struct interior node (left right) #:transparent) (struct leaf node (val) #:transparent) (define (node<=? x y) (<= (node-freq x) (node-freq y))) (define (make-huffman-tree leaves) (define a-heap (make-heap node<=?)) (heap-add-all! a-heap leaves) (for ([i (sub1 (length leaves))]) (define min-1 (heap-min a-heap)) (heap-remove-min! a-heap) (define min-2 (heap-min a-heap)) (heap-remove-min! a-heap) (heap-add! a-heap (interior (+ (node-freq min-1) (node-freq min-2)) min-1 min-2))) (heap-min a-heap)) (define (string->huffman-tree str) (define ht (make-hash)) (define n (sequence-length str)) (for ([ch str]) (hash-update! ht ch add1 (λ () 0))) (make-huffman-tree (for/list ([(k v) (in-hash ht)]) (leaf (/ v n) k)))) (define (make-encoder a-tree) (define dict (huffman-tree->dictionary a-tree)) (lambda (a-str) (list->bit-vector (apply append (for/list ([ch a-str]) (hash-ref dict ch)))))) (define (huffman-tree->dictionary a-node) (define ht (make-hash)) (let loop ([a-node a-node] [path/rev '()]) (cond [(interior? a-node) (loop (interior-left a-node) (cons #f path/rev)) (loop (interior-right a-node) (cons #t path/rev))] [(leaf? a-node) (hash-set! ht (reverse path/rev) (leaf-val a-node))])) (for/hash ([(k v) ht]) (values v k))) (define (make-decoder a-tree) (lambda (a-bitvector) (define-values (decoded/rev _) (for/fold ([decoded/rev '()] [a-node a-tree]) ([bit a-bitvector]) (define next-node (cond [(not bit) (interior-left a-node)] [else (interior-right a-node)])) (cond [(leaf? next-node) (values (cons (leaf-val next-node) decoded/rev) a-tree)] [else (values decoded/rev next-node)]))) (apply string (reverse decoded/rev)))) (define msg "this is an example for huffman encoding") (define tree (string->huffman-tree msg)) (huffman-tree->dictionary tree) (define encode (make-encoder tree)) (define encoded (encode msg)) (bit-vector->string encoded) (define decode (make-decoder tree)) (decode encoded)
#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#.
#lang racket (require data/heap data/bit-vector) (struct node (freq) #:transparent) (struct interior node (left right) #:transparent) (struct leaf node (val) #:transparent) (define (node<=? x y) (<= (node-freq x) (node-freq y))) (define (make-huffman-tree leaves) (define a-heap (make-heap node<=?)) (heap-add-all! a-heap leaves) (for ([i (sub1 (length leaves))]) (define min-1 (heap-min a-heap)) (heap-remove-min! a-heap) (define min-2 (heap-min a-heap)) (heap-remove-min! a-heap) (heap-add! a-heap (interior (+ (node-freq min-1) (node-freq min-2)) min-1 min-2))) (heap-min a-heap)) (define (string->huffman-tree str) (define ht (make-hash)) (define n (sequence-length str)) (for ([ch str]) (hash-update! ht ch add1 (λ () 0))) (make-huffman-tree (for/list ([(k v) (in-hash ht)]) (leaf (/ v n) k)))) (define (make-encoder a-tree) (define dict (huffman-tree->dictionary a-tree)) (lambda (a-str) (list->bit-vector (apply append (for/list ([ch a-str]) (hash-ref dict ch)))))) (define (huffman-tree->dictionary a-node) (define ht (make-hash)) (let loop ([a-node a-node] [path/rev '()]) (cond [(interior? a-node) (loop (interior-left a-node) (cons #f path/rev)) (loop (interior-right a-node) (cons #t path/rev))] [(leaf? a-node) (hash-set! ht (reverse path/rev) (leaf-val a-node))])) (for/hash ([(k v) ht]) (values v k))) (define (make-decoder a-tree) (lambda (a-bitvector) (define-values (decoded/rev _) (for/fold ([decoded/rev '()] [a-node a-tree]) ([bit a-bitvector]) (define next-node (cond [(not bit) (interior-left a-node)] [else (interior-right a-node)])) (cond [(leaf? next-node) (values (cons (leaf-val next-node) decoded/rev) a-tree)] [else (values decoded/rev next-node)]))) (apply string (reverse decoded/rev)))) (define msg "this is an example for huffman encoding") (define tree (string->huffman-tree msg)) (huffman-tree->dictionary tree) (define encode (make-encoder tree)) (define encoded (encode msg)) (bit-vector->string encoded) (define decode (make-decoder tree)) (decode encoded)
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 Racket to C++ with equivalent syntax and logic.
#lang racket (require data/heap data/bit-vector) (struct node (freq) #:transparent) (struct interior node (left right) #:transparent) (struct leaf node (val) #:transparent) (define (node<=? x y) (<= (node-freq x) (node-freq y))) (define (make-huffman-tree leaves) (define a-heap (make-heap node<=?)) (heap-add-all! a-heap leaves) (for ([i (sub1 (length leaves))]) (define min-1 (heap-min a-heap)) (heap-remove-min! a-heap) (define min-2 (heap-min a-heap)) (heap-remove-min! a-heap) (heap-add! a-heap (interior (+ (node-freq min-1) (node-freq min-2)) min-1 min-2))) (heap-min a-heap)) (define (string->huffman-tree str) (define ht (make-hash)) (define n (sequence-length str)) (for ([ch str]) (hash-update! ht ch add1 (λ () 0))) (make-huffman-tree (for/list ([(k v) (in-hash ht)]) (leaf (/ v n) k)))) (define (make-encoder a-tree) (define dict (huffman-tree->dictionary a-tree)) (lambda (a-str) (list->bit-vector (apply append (for/list ([ch a-str]) (hash-ref dict ch)))))) (define (huffman-tree->dictionary a-node) (define ht (make-hash)) (let loop ([a-node a-node] [path/rev '()]) (cond [(interior? a-node) (loop (interior-left a-node) (cons #f path/rev)) (loop (interior-right a-node) (cons #t path/rev))] [(leaf? a-node) (hash-set! ht (reverse path/rev) (leaf-val a-node))])) (for/hash ([(k v) ht]) (values v k))) (define (make-decoder a-tree) (lambda (a-bitvector) (define-values (decoded/rev _) (for/fold ([decoded/rev '()] [a-node a-tree]) ([bit a-bitvector]) (define next-node (cond [(not bit) (interior-left a-node)] [else (interior-right a-node)])) (cond [(leaf? next-node) (values (cons (leaf-val next-node) decoded/rev) a-tree)] [else (values decoded/rev next-node)]))) (apply string (reverse decoded/rev)))) (define msg "this is an example for huffman encoding") (define tree (string->huffman-tree msg)) (huffman-tree->dictionary tree) (define encode (make-encoder tree)) (define encoded (encode msg)) (bit-vector->string encoded) (define decode (make-decoder tree)) (decode encoded)
#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 code in Java as shown below in Racket.
#lang racket (require data/heap data/bit-vector) (struct node (freq) #:transparent) (struct interior node (left right) #:transparent) (struct leaf node (val) #:transparent) (define (node<=? x y) (<= (node-freq x) (node-freq y))) (define (make-huffman-tree leaves) (define a-heap (make-heap node<=?)) (heap-add-all! a-heap leaves) (for ([i (sub1 (length leaves))]) (define min-1 (heap-min a-heap)) (heap-remove-min! a-heap) (define min-2 (heap-min a-heap)) (heap-remove-min! a-heap) (heap-add! a-heap (interior (+ (node-freq min-1) (node-freq min-2)) min-1 min-2))) (heap-min a-heap)) (define (string->huffman-tree str) (define ht (make-hash)) (define n (sequence-length str)) (for ([ch str]) (hash-update! ht ch add1 (λ () 0))) (make-huffman-tree (for/list ([(k v) (in-hash ht)]) (leaf (/ v n) k)))) (define (make-encoder a-tree) (define dict (huffman-tree->dictionary a-tree)) (lambda (a-str) (list->bit-vector (apply append (for/list ([ch a-str]) (hash-ref dict ch)))))) (define (huffman-tree->dictionary a-node) (define ht (make-hash)) (let loop ([a-node a-node] [path/rev '()]) (cond [(interior? a-node) (loop (interior-left a-node) (cons #f path/rev)) (loop (interior-right a-node) (cons #t path/rev))] [(leaf? a-node) (hash-set! ht (reverse path/rev) (leaf-val a-node))])) (for/hash ([(k v) ht]) (values v k))) (define (make-decoder a-tree) (lambda (a-bitvector) (define-values (decoded/rev _) (for/fold ([decoded/rev '()] [a-node a-tree]) ([bit a-bitvector]) (define next-node (cond [(not bit) (interior-left a-node)] [else (interior-right a-node)])) (cond [(leaf? next-node) (values (cons (leaf-val next-node) decoded/rev) a-tree)] [else (values decoded/rev next-node)]))) (apply string (reverse decoded/rev)))) (define msg "this is an example for huffman encoding") (define tree (string->huffman-tree msg)) (huffman-tree->dictionary tree) (define encode (make-encoder tree)) (define encoded (encode msg)) (bit-vector->string encoded) (define decode (make-decoder tree)) (decode encoded)
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 Racket function in Python with identical behavior.
#lang racket (require data/heap data/bit-vector) (struct node (freq) #:transparent) (struct interior node (left right) #:transparent) (struct leaf node (val) #:transparent) (define (node<=? x y) (<= (node-freq x) (node-freq y))) (define (make-huffman-tree leaves) (define a-heap (make-heap node<=?)) (heap-add-all! a-heap leaves) (for ([i (sub1 (length leaves))]) (define min-1 (heap-min a-heap)) (heap-remove-min! a-heap) (define min-2 (heap-min a-heap)) (heap-remove-min! a-heap) (heap-add! a-heap (interior (+ (node-freq min-1) (node-freq min-2)) min-1 min-2))) (heap-min a-heap)) (define (string->huffman-tree str) (define ht (make-hash)) (define n (sequence-length str)) (for ([ch str]) (hash-update! ht ch add1 (λ () 0))) (make-huffman-tree (for/list ([(k v) (in-hash ht)]) (leaf (/ v n) k)))) (define (make-encoder a-tree) (define dict (huffman-tree->dictionary a-tree)) (lambda (a-str) (list->bit-vector (apply append (for/list ([ch a-str]) (hash-ref dict ch)))))) (define (huffman-tree->dictionary a-node) (define ht (make-hash)) (let loop ([a-node a-node] [path/rev '()]) (cond [(interior? a-node) (loop (interior-left a-node) (cons #f path/rev)) (loop (interior-right a-node) (cons #t path/rev))] [(leaf? a-node) (hash-set! ht (reverse path/rev) (leaf-val a-node))])) (for/hash ([(k v) ht]) (values v k))) (define (make-decoder a-tree) (lambda (a-bitvector) (define-values (decoded/rev _) (for/fold ([decoded/rev '()] [a-node a-tree]) ([bit a-bitvector]) (define next-node (cond [(not bit) (interior-left a-node)] [else (interior-right a-node)])) (cond [(leaf? next-node) (values (cons (leaf-val next-node) decoded/rev) a-tree)] [else (values decoded/rev next-node)]))) (apply string (reverse decoded/rev)))) (define msg "this is an example for huffman encoding") (define tree (string->huffman-tree msg)) (huffman-tree->dictionary tree) (define encode (make-encoder tree)) (define encoded (encode msg)) (bit-vector->string encoded) (define decode (make-decoder tree)) (decode encoded)
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 Racket code into Go without altering its purpose.
#lang racket (require data/heap data/bit-vector) (struct node (freq) #:transparent) (struct interior node (left right) #:transparent) (struct leaf node (val) #:transparent) (define (node<=? x y) (<= (node-freq x) (node-freq y))) (define (make-huffman-tree leaves) (define a-heap (make-heap node<=?)) (heap-add-all! a-heap leaves) (for ([i (sub1 (length leaves))]) (define min-1 (heap-min a-heap)) (heap-remove-min! a-heap) (define min-2 (heap-min a-heap)) (heap-remove-min! a-heap) (heap-add! a-heap (interior (+ (node-freq min-1) (node-freq min-2)) min-1 min-2))) (heap-min a-heap)) (define (string->huffman-tree str) (define ht (make-hash)) (define n (sequence-length str)) (for ([ch str]) (hash-update! ht ch add1 (λ () 0))) (make-huffman-tree (for/list ([(k v) (in-hash ht)]) (leaf (/ v n) k)))) (define (make-encoder a-tree) (define dict (huffman-tree->dictionary a-tree)) (lambda (a-str) (list->bit-vector (apply append (for/list ([ch a-str]) (hash-ref dict ch)))))) (define (huffman-tree->dictionary a-node) (define ht (make-hash)) (let loop ([a-node a-node] [path/rev '()]) (cond [(interior? a-node) (loop (interior-left a-node) (cons #f path/rev)) (loop (interior-right a-node) (cons #t path/rev))] [(leaf? a-node) (hash-set! ht (reverse path/rev) (leaf-val a-node))])) (for/hash ([(k v) ht]) (values v k))) (define (make-decoder a-tree) (lambda (a-bitvector) (define-values (decoded/rev _) (for/fold ([decoded/rev '()] [a-node a-tree]) ([bit a-bitvector]) (define next-node (cond [(not bit) (interior-left a-node)] [else (interior-right a-node)])) (cond [(leaf? next-node) (values (cons (leaf-val next-node) decoded/rev) a-tree)] [else (values decoded/rev next-node)]))) (apply string (reverse decoded/rev)))) (define msg "this is an example for huffman encoding") (define tree (string->huffman-tree msg)) (huffman-tree->dictionary tree) (define encode (make-encoder tree)) (define encoded (encode msg)) (bit-vector->string encoded) (define decode (make-decoder tree)) (decode encoded)
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 a C translation of this REXX snippet without changing its computational steps.
* 27.12.2013 Walter Pachl * 29.12.2013 -"- changed for test of s=xrange('00'x,'ff'x) * 14.03.2018 -"- use format instead of right to diagnose size poblems * Stem m contains eventually the following node data * m.i.0id Node id * m.i.0c character * m.i.0o number of occurrences * m.i.0l left child * m.i.0r right child * m.i.0f father * m.i.0d digit (0 or 1) * m.i.0t 1=a terminal node 0=an intermediate or the top node *--------------------------------------------------------------------*/ Parse Arg s If s='' Then s='this is an example for huffman encoding' Say 'We encode this string:' Say s debug=0 o.=0 c.=0 codel.=0 code.='' father.=0 cl='' do i=1 To length(s) Call memorize substr(s,i,1) End If debug Then Do Do i=1 To c.0 c=c.i Say i c o.c End End n.=0 Do i=1 To c.0 c=c.i n.i.0c=c n.i.0o=o.c n.i.0id=i Call dbg i n.i.0id n.i.0c n.i.0o End n=c.0 m.=0 Do i=1 To n Do j=1 To m.0 If m.j.0o>n.i.0o Then Leave End Do k=m.0 To j By -1 k1=k+1 m.k1.0id=m.k.0id m.k1.0c =m.k.0c m.k1.0o =m.k.0o m.k1.0t =m.k.0t End m.j.0id=i m.j.0c =n.i.0c m.j.0o =n.i.0o m.j.0t =1 m.0=m.0+1 End If debug Then Call show Do While pairs()>1 Call mknode If debug Then Call show End Call show c.=0 Do i=1 To m.0 If m.i.0t Then Do code=m.i.0d node=m.i.0id Do fi=1 To 1000 fid=father.node If fid<>0 Then Do fidz=zeile(fid) code=m.fidz.0d||code node=fid End Else Leave End If length(code)>1 Then code=substr(code,2) call dbg m.i.0c '->' code char=m.i.0c code.char=code z=codel.0+1 codel.z=code codel.0=z char.code=char End End Call show_char2code codes.=0 Do j=1 To codel.0 z=codes.0+1 code=codel.j codes.z=code chars.z=char.code codes.0=z Call dbg codes.z '----->' chars.z End sc='' Do i=1 To length(s) c=substr(s,i,1) sc=sc||code.c End Say 'Length of encoded string:' length(sc) Do i=1 To length(sc) by 70 Say substr(sc,i,70) End sr='' Do si=1 To 999 While sc<>'' Do i=codes.0 To 1 By -1 cl=length(codes.i) If left(sc,cl)==codes.i Then Do sr=sr||chars.i sc=substr(sc,cl+1) Leave End End End Say 'Input ="'s'"' Say 'result="'sr'"' Exit show: * show all lines representing node data *--------------------------------------------------------------------*/ Say ' i pp id c f l r d' Do i=1 To m.0 Say format(i,3) format(m.i.0o,4) format(m.i.0id,3), format(m.i.0f,3) format(m.i.0l,3) format(m.i.0r,3) m.i.0d m.i.0t End Call dbg copies('-',21) Return pairs: Procedure Expose m. * return number of fatherless nodes *--------------------------------------------------------------------*/ res=0 Do i=1 To m.0 If m.i.0f=0 Then res=res+1 End Return res mknode: * construct and store a new intermediate or the top node *--------------------------------------------------------------------*/ new.=0 ni=m.0+1 Do i=1 To m.0 If m.i.0f=0 Then Do z=m.i.0id If new.0l=0 Then Do new.0l=z new.0o=m.i.0o m.i.0f=ni m.i.0d='0' father.z=ni End Else Do new.0r=z new.0o=new.0o+m.i.0o m.i.0f=ni m.i.0d=1 father.z=ni Leave End End End Do i=1 To m.0 If m.i.0o>=new.0o Then Do Do k=m.0 To i By -1 k1=k+1 m.k1.0id=m.k.0id m.k1.0o =m.k.0o m.k1.0c =m.k.0c m.k1.0l =m.k.0l m.k1.0r =m.k.0r m.k1.0f =m.k.0f m.k1.0d =m.k.0d m.k1.0t =m.k.0t End Leave End End m.i.0id=ni m.i.0c ='*' m.i.0o =new.0o m.i.0l =new.0l m.i.0r =new.0r m.i.0t =0 father.ni=0 m.0=ni Return zeile: * find and return line number containing node-id *--------------------------------------------------------------------*/ do fidz=1 To m.0 If m.fidz.0id=arg(1) Then Return fidz End Call dbg arg(1) 'not found' Pull . dbg: * Show text if debug is enabled *--------------------------------------------------------------------*/ If debug=1 Then Say arg(1) Return memorize: Procedure Expose c. o. * store characters and corresponding occurrences *--------------------------------------------------------------------*/ Parse Arg c If o.c=0 Then Do z=c.0+1 c.z=c c.0=z End o.c=o.c+1 Return show_char2code: * show used characters and corresponding codes *--------------------------------------------------------------------*/ cl=xrange('00'x,'ff'x) Say 'char --> code' Do While cl<>'' Parse Var cl c +1 cl If code.c<>'' Then Say ' 'c '-->' code.c End Return
#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 REXX block to C++, preserving its control flow and logic.
* 27.12.2013 Walter Pachl * 29.12.2013 -"- changed for test of s=xrange('00'x,'ff'x) * 14.03.2018 -"- use format instead of right to diagnose size poblems * Stem m contains eventually the following node data * m.i.0id Node id * m.i.0c character * m.i.0o number of occurrences * m.i.0l left child * m.i.0r right child * m.i.0f father * m.i.0d digit (0 or 1) * m.i.0t 1=a terminal node 0=an intermediate or the top node *--------------------------------------------------------------------*/ Parse Arg s If s='' Then s='this is an example for huffman encoding' Say 'We encode this string:' Say s debug=0 o.=0 c.=0 codel.=0 code.='' father.=0 cl='' do i=1 To length(s) Call memorize substr(s,i,1) End If debug Then Do Do i=1 To c.0 c=c.i Say i c o.c End End n.=0 Do i=1 To c.0 c=c.i n.i.0c=c n.i.0o=o.c n.i.0id=i Call dbg i n.i.0id n.i.0c n.i.0o End n=c.0 m.=0 Do i=1 To n Do j=1 To m.0 If m.j.0o>n.i.0o Then Leave End Do k=m.0 To j By -1 k1=k+1 m.k1.0id=m.k.0id m.k1.0c =m.k.0c m.k1.0o =m.k.0o m.k1.0t =m.k.0t End m.j.0id=i m.j.0c =n.i.0c m.j.0o =n.i.0o m.j.0t =1 m.0=m.0+1 End If debug Then Call show Do While pairs()>1 Call mknode If debug Then Call show End Call show c.=0 Do i=1 To m.0 If m.i.0t Then Do code=m.i.0d node=m.i.0id Do fi=1 To 1000 fid=father.node If fid<>0 Then Do fidz=zeile(fid) code=m.fidz.0d||code node=fid End Else Leave End If length(code)>1 Then code=substr(code,2) call dbg m.i.0c '->' code char=m.i.0c code.char=code z=codel.0+1 codel.z=code codel.0=z char.code=char End End Call show_char2code codes.=0 Do j=1 To codel.0 z=codes.0+1 code=codel.j codes.z=code chars.z=char.code codes.0=z Call dbg codes.z '----->' chars.z End sc='' Do i=1 To length(s) c=substr(s,i,1) sc=sc||code.c End Say 'Length of encoded string:' length(sc) Do i=1 To length(sc) by 70 Say substr(sc,i,70) End sr='' Do si=1 To 999 While sc<>'' Do i=codes.0 To 1 By -1 cl=length(codes.i) If left(sc,cl)==codes.i Then Do sr=sr||chars.i sc=substr(sc,cl+1) Leave End End End Say 'Input ="'s'"' Say 'result="'sr'"' Exit show: * show all lines representing node data *--------------------------------------------------------------------*/ Say ' i pp id c f l r d' Do i=1 To m.0 Say format(i,3) format(m.i.0o,4) format(m.i.0id,3), format(m.i.0f,3) format(m.i.0l,3) format(m.i.0r,3) m.i.0d m.i.0t End Call dbg copies('-',21) Return pairs: Procedure Expose m. * return number of fatherless nodes *--------------------------------------------------------------------*/ res=0 Do i=1 To m.0 If m.i.0f=0 Then res=res+1 End Return res mknode: * construct and store a new intermediate or the top node *--------------------------------------------------------------------*/ new.=0 ni=m.0+1 Do i=1 To m.0 If m.i.0f=0 Then Do z=m.i.0id If new.0l=0 Then Do new.0l=z new.0o=m.i.0o m.i.0f=ni m.i.0d='0' father.z=ni End Else Do new.0r=z new.0o=new.0o+m.i.0o m.i.0f=ni m.i.0d=1 father.z=ni Leave End End End Do i=1 To m.0 If m.i.0o>=new.0o Then Do Do k=m.0 To i By -1 k1=k+1 m.k1.0id=m.k.0id m.k1.0o =m.k.0o m.k1.0c =m.k.0c m.k1.0l =m.k.0l m.k1.0r =m.k.0r m.k1.0f =m.k.0f m.k1.0d =m.k.0d m.k1.0t =m.k.0t End Leave End End m.i.0id=ni m.i.0c ='*' m.i.0o =new.0o m.i.0l =new.0l m.i.0r =new.0r m.i.0t =0 father.ni=0 m.0=ni Return zeile: * find and return line number containing node-id *--------------------------------------------------------------------*/ do fidz=1 To m.0 If m.fidz.0id=arg(1) Then Return fidz End Call dbg arg(1) 'not found' Pull . dbg: * Show text if debug is enabled *--------------------------------------------------------------------*/ If debug=1 Then Say arg(1) Return memorize: Procedure Expose c. o. * store characters and corresponding occurrences *--------------------------------------------------------------------*/ Parse Arg c If o.c=0 Then Do z=c.0+1 c.z=c c.0=z End o.c=o.c+1 Return show_char2code: * show used characters and corresponding codes *--------------------------------------------------------------------*/ cl=xrange('00'x,'ff'x) Say 'char --> code' Do While cl<>'' Parse Var cl c +1 cl If code.c<>'' Then Say ' 'c '-->' code.c End Return
#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 Java as shown in this REXX implementation.
* 27.12.2013 Walter Pachl * 29.12.2013 -"- changed for test of s=xrange('00'x,'ff'x) * 14.03.2018 -"- use format instead of right to diagnose size poblems * Stem m contains eventually the following node data * m.i.0id Node id * m.i.0c character * m.i.0o number of occurrences * m.i.0l left child * m.i.0r right child * m.i.0f father * m.i.0d digit (0 or 1) * m.i.0t 1=a terminal node 0=an intermediate or the top node *--------------------------------------------------------------------*/ Parse Arg s If s='' Then s='this is an example for huffman encoding' Say 'We encode this string:' Say s debug=0 o.=0 c.=0 codel.=0 code.='' father.=0 cl='' do i=1 To length(s) Call memorize substr(s,i,1) End If debug Then Do Do i=1 To c.0 c=c.i Say i c o.c End End n.=0 Do i=1 To c.0 c=c.i n.i.0c=c n.i.0o=o.c n.i.0id=i Call dbg i n.i.0id n.i.0c n.i.0o End n=c.0 m.=0 Do i=1 To n Do j=1 To m.0 If m.j.0o>n.i.0o Then Leave End Do k=m.0 To j By -1 k1=k+1 m.k1.0id=m.k.0id m.k1.0c =m.k.0c m.k1.0o =m.k.0o m.k1.0t =m.k.0t End m.j.0id=i m.j.0c =n.i.0c m.j.0o =n.i.0o m.j.0t =1 m.0=m.0+1 End If debug Then Call show Do While pairs()>1 Call mknode If debug Then Call show End Call show c.=0 Do i=1 To m.0 If m.i.0t Then Do code=m.i.0d node=m.i.0id Do fi=1 To 1000 fid=father.node If fid<>0 Then Do fidz=zeile(fid) code=m.fidz.0d||code node=fid End Else Leave End If length(code)>1 Then code=substr(code,2) call dbg m.i.0c '->' code char=m.i.0c code.char=code z=codel.0+1 codel.z=code codel.0=z char.code=char End End Call show_char2code codes.=0 Do j=1 To codel.0 z=codes.0+1 code=codel.j codes.z=code chars.z=char.code codes.0=z Call dbg codes.z '----->' chars.z End sc='' Do i=1 To length(s) c=substr(s,i,1) sc=sc||code.c End Say 'Length of encoded string:' length(sc) Do i=1 To length(sc) by 70 Say substr(sc,i,70) End sr='' Do si=1 To 999 While sc<>'' Do i=codes.0 To 1 By -1 cl=length(codes.i) If left(sc,cl)==codes.i Then Do sr=sr||chars.i sc=substr(sc,cl+1) Leave End End End Say 'Input ="'s'"' Say 'result="'sr'"' Exit show: * show all lines representing node data *--------------------------------------------------------------------*/ Say ' i pp id c f l r d' Do i=1 To m.0 Say format(i,3) format(m.i.0o,4) format(m.i.0id,3), format(m.i.0f,3) format(m.i.0l,3) format(m.i.0r,3) m.i.0d m.i.0t End Call dbg copies('-',21) Return pairs: Procedure Expose m. * return number of fatherless nodes *--------------------------------------------------------------------*/ res=0 Do i=1 To m.0 If m.i.0f=0 Then res=res+1 End Return res mknode: * construct and store a new intermediate or the top node *--------------------------------------------------------------------*/ new.=0 ni=m.0+1 Do i=1 To m.0 If m.i.0f=0 Then Do z=m.i.0id If new.0l=0 Then Do new.0l=z new.0o=m.i.0o m.i.0f=ni m.i.0d='0' father.z=ni End Else Do new.0r=z new.0o=new.0o+m.i.0o m.i.0f=ni m.i.0d=1 father.z=ni Leave End End End Do i=1 To m.0 If m.i.0o>=new.0o Then Do Do k=m.0 To i By -1 k1=k+1 m.k1.0id=m.k.0id m.k1.0o =m.k.0o m.k1.0c =m.k.0c m.k1.0l =m.k.0l m.k1.0r =m.k.0r m.k1.0f =m.k.0f m.k1.0d =m.k.0d m.k1.0t =m.k.0t End Leave End End m.i.0id=ni m.i.0c ='*' m.i.0o =new.0o m.i.0l =new.0l m.i.0r =new.0r m.i.0t =0 father.ni=0 m.0=ni Return zeile: * find and return line number containing node-id *--------------------------------------------------------------------*/ do fidz=1 To m.0 If m.fidz.0id=arg(1) Then Return fidz End Call dbg arg(1) 'not found' Pull . dbg: * Show text if debug is enabled *--------------------------------------------------------------------*/ If debug=1 Then Say arg(1) Return memorize: Procedure Expose c. o. * store characters and corresponding occurrences *--------------------------------------------------------------------*/ Parse Arg c If o.c=0 Then Do z=c.0+1 c.z=c c.0=z End o.c=o.c+1 Return show_char2code: * show used characters and corresponding codes *--------------------------------------------------------------------*/ cl=xrange('00'x,'ff'x) Say 'char --> code' Do While cl<>'' Parse Var cl c +1 cl If code.c<>'' Then Say ' 'c '-->' code.c End Return
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 REXX function in Python with identical behavior.
* 27.12.2013 Walter Pachl * 29.12.2013 -"- changed for test of s=xrange('00'x,'ff'x) * 14.03.2018 -"- use format instead of right to diagnose size poblems * Stem m contains eventually the following node data * m.i.0id Node id * m.i.0c character * m.i.0o number of occurrences * m.i.0l left child * m.i.0r right child * m.i.0f father * m.i.0d digit (0 or 1) * m.i.0t 1=a terminal node 0=an intermediate or the top node *--------------------------------------------------------------------*/ Parse Arg s If s='' Then s='this is an example for huffman encoding' Say 'We encode this string:' Say s debug=0 o.=0 c.=0 codel.=0 code.='' father.=0 cl='' do i=1 To length(s) Call memorize substr(s,i,1) End If debug Then Do Do i=1 To c.0 c=c.i Say i c o.c End End n.=0 Do i=1 To c.0 c=c.i n.i.0c=c n.i.0o=o.c n.i.0id=i Call dbg i n.i.0id n.i.0c n.i.0o End n=c.0 m.=0 Do i=1 To n Do j=1 To m.0 If m.j.0o>n.i.0o Then Leave End Do k=m.0 To j By -1 k1=k+1 m.k1.0id=m.k.0id m.k1.0c =m.k.0c m.k1.0o =m.k.0o m.k1.0t =m.k.0t End m.j.0id=i m.j.0c =n.i.0c m.j.0o =n.i.0o m.j.0t =1 m.0=m.0+1 End If debug Then Call show Do While pairs()>1 Call mknode If debug Then Call show End Call show c.=0 Do i=1 To m.0 If m.i.0t Then Do code=m.i.0d node=m.i.0id Do fi=1 To 1000 fid=father.node If fid<>0 Then Do fidz=zeile(fid) code=m.fidz.0d||code node=fid End Else Leave End If length(code)>1 Then code=substr(code,2) call dbg m.i.0c '->' code char=m.i.0c code.char=code z=codel.0+1 codel.z=code codel.0=z char.code=char End End Call show_char2code codes.=0 Do j=1 To codel.0 z=codes.0+1 code=codel.j codes.z=code chars.z=char.code codes.0=z Call dbg codes.z '----->' chars.z End sc='' Do i=1 To length(s) c=substr(s,i,1) sc=sc||code.c End Say 'Length of encoded string:' length(sc) Do i=1 To length(sc) by 70 Say substr(sc,i,70) End sr='' Do si=1 To 999 While sc<>'' Do i=codes.0 To 1 By -1 cl=length(codes.i) If left(sc,cl)==codes.i Then Do sr=sr||chars.i sc=substr(sc,cl+1) Leave End End End Say 'Input ="'s'"' Say 'result="'sr'"' Exit show: * show all lines representing node data *--------------------------------------------------------------------*/ Say ' i pp id c f l r d' Do i=1 To m.0 Say format(i,3) format(m.i.0o,4) format(m.i.0id,3), format(m.i.0f,3) format(m.i.0l,3) format(m.i.0r,3) m.i.0d m.i.0t End Call dbg copies('-',21) Return pairs: Procedure Expose m. * return number of fatherless nodes *--------------------------------------------------------------------*/ res=0 Do i=1 To m.0 If m.i.0f=0 Then res=res+1 End Return res mknode: * construct and store a new intermediate or the top node *--------------------------------------------------------------------*/ new.=0 ni=m.0+1 Do i=1 To m.0 If m.i.0f=0 Then Do z=m.i.0id If new.0l=0 Then Do new.0l=z new.0o=m.i.0o m.i.0f=ni m.i.0d='0' father.z=ni End Else Do new.0r=z new.0o=new.0o+m.i.0o m.i.0f=ni m.i.0d=1 father.z=ni Leave End End End Do i=1 To m.0 If m.i.0o>=new.0o Then Do Do k=m.0 To i By -1 k1=k+1 m.k1.0id=m.k.0id m.k1.0o =m.k.0o m.k1.0c =m.k.0c m.k1.0l =m.k.0l m.k1.0r =m.k.0r m.k1.0f =m.k.0f m.k1.0d =m.k.0d m.k1.0t =m.k.0t End Leave End End m.i.0id=ni m.i.0c ='*' m.i.0o =new.0o m.i.0l =new.0l m.i.0r =new.0r m.i.0t =0 father.ni=0 m.0=ni Return zeile: * find and return line number containing node-id *--------------------------------------------------------------------*/ do fidz=1 To m.0 If m.fidz.0id=arg(1) Then Return fidz End Call dbg arg(1) 'not found' Pull . dbg: * Show text if debug is enabled *--------------------------------------------------------------------*/ If debug=1 Then Say arg(1) Return memorize: Procedure Expose c. o. * store characters and corresponding occurrences *--------------------------------------------------------------------*/ Parse Arg c If o.c=0 Then Do z=c.0+1 c.z=c c.0=z End o.c=o.c+1 Return show_char2code: * show used characters and corresponding codes *--------------------------------------------------------------------*/ cl=xrange('00'x,'ff'x) Say 'char --> code' Do While cl<>'' Parse Var cl c +1 cl If code.c<>'' Then Say ' 'c '-->' code.c End Return
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])
Generate an equivalent Go version of this REXX code.
* 27.12.2013 Walter Pachl * 29.12.2013 -"- changed for test of s=xrange('00'x,'ff'x) * 14.03.2018 -"- use format instead of right to diagnose size poblems * Stem m contains eventually the following node data * m.i.0id Node id * m.i.0c character * m.i.0o number of occurrences * m.i.0l left child * m.i.0r right child * m.i.0f father * m.i.0d digit (0 or 1) * m.i.0t 1=a terminal node 0=an intermediate or the top node *--------------------------------------------------------------------*/ Parse Arg s If s='' Then s='this is an example for huffman encoding' Say 'We encode this string:' Say s debug=0 o.=0 c.=0 codel.=0 code.='' father.=0 cl='' do i=1 To length(s) Call memorize substr(s,i,1) End If debug Then Do Do i=1 To c.0 c=c.i Say i c o.c End End n.=0 Do i=1 To c.0 c=c.i n.i.0c=c n.i.0o=o.c n.i.0id=i Call dbg i n.i.0id n.i.0c n.i.0o End n=c.0 m.=0 Do i=1 To n Do j=1 To m.0 If m.j.0o>n.i.0o Then Leave End Do k=m.0 To j By -1 k1=k+1 m.k1.0id=m.k.0id m.k1.0c =m.k.0c m.k1.0o =m.k.0o m.k1.0t =m.k.0t End m.j.0id=i m.j.0c =n.i.0c m.j.0o =n.i.0o m.j.0t =1 m.0=m.0+1 End If debug Then Call show Do While pairs()>1 Call mknode If debug Then Call show End Call show c.=0 Do i=1 To m.0 If m.i.0t Then Do code=m.i.0d node=m.i.0id Do fi=1 To 1000 fid=father.node If fid<>0 Then Do fidz=zeile(fid) code=m.fidz.0d||code node=fid End Else Leave End If length(code)>1 Then code=substr(code,2) call dbg m.i.0c '->' code char=m.i.0c code.char=code z=codel.0+1 codel.z=code codel.0=z char.code=char End End Call show_char2code codes.=0 Do j=1 To codel.0 z=codes.0+1 code=codel.j codes.z=code chars.z=char.code codes.0=z Call dbg codes.z '----->' chars.z End sc='' Do i=1 To length(s) c=substr(s,i,1) sc=sc||code.c End Say 'Length of encoded string:' length(sc) Do i=1 To length(sc) by 70 Say substr(sc,i,70) End sr='' Do si=1 To 999 While sc<>'' Do i=codes.0 To 1 By -1 cl=length(codes.i) If left(sc,cl)==codes.i Then Do sr=sr||chars.i sc=substr(sc,cl+1) Leave End End End Say 'Input ="'s'"' Say 'result="'sr'"' Exit show: * show all lines representing node data *--------------------------------------------------------------------*/ Say ' i pp id c f l r d' Do i=1 To m.0 Say format(i,3) format(m.i.0o,4) format(m.i.0id,3), format(m.i.0f,3) format(m.i.0l,3) format(m.i.0r,3) m.i.0d m.i.0t End Call dbg copies('-',21) Return pairs: Procedure Expose m. * return number of fatherless nodes *--------------------------------------------------------------------*/ res=0 Do i=1 To m.0 If m.i.0f=0 Then res=res+1 End Return res mknode: * construct and store a new intermediate or the top node *--------------------------------------------------------------------*/ new.=0 ni=m.0+1 Do i=1 To m.0 If m.i.0f=0 Then Do z=m.i.0id If new.0l=0 Then Do new.0l=z new.0o=m.i.0o m.i.0f=ni m.i.0d='0' father.z=ni End Else Do new.0r=z new.0o=new.0o+m.i.0o m.i.0f=ni m.i.0d=1 father.z=ni Leave End End End Do i=1 To m.0 If m.i.0o>=new.0o Then Do Do k=m.0 To i By -1 k1=k+1 m.k1.0id=m.k.0id m.k1.0o =m.k.0o m.k1.0c =m.k.0c m.k1.0l =m.k.0l m.k1.0r =m.k.0r m.k1.0f =m.k.0f m.k1.0d =m.k.0d m.k1.0t =m.k.0t End Leave End End m.i.0id=ni m.i.0c ='*' m.i.0o =new.0o m.i.0l =new.0l m.i.0r =new.0r m.i.0t =0 father.ni=0 m.0=ni Return zeile: * find and return line number containing node-id *--------------------------------------------------------------------*/ do fidz=1 To m.0 If m.fidz.0id=arg(1) Then Return fidz End Call dbg arg(1) 'not found' Pull . dbg: * Show text if debug is enabled *--------------------------------------------------------------------*/ If debug=1 Then Say arg(1) Return memorize: Procedure Expose c. o. * store characters and corresponding occurrences *--------------------------------------------------------------------*/ Parse Arg c If o.c=0 Then Do z=c.0+1 c.z=c c.0=z End o.c=o.c+1 Return show_char2code: * show used characters and corresponding codes *--------------------------------------------------------------------*/ cl=xrange('00'x,'ff'x) Say 'char --> code' Do While cl<>'' Parse Var cl c +1 cl If code.c<>'' Then Say ' 'c '-->' code.c End Return
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 this program in C while keeping its functionality equivalent to the Ruby version.
require 'priority_queue' def huffman_encoding(str) char_count = Hash.new(0) str.each_char {|c| char_count[c] += 1} pq = CPriorityQueue.new char_count.each {|char, count| pq.push(char, count)} while pq.length > 1 key1, prio1 = pq.delete_min key2, prio2 = pq.delete_min pq.push([key1, key2], prio1 + prio2) end Hash[*generate_encoding(pq.min_key)] end def generate_encoding(ary, prefix="") case ary when Array generate_encoding(ary[0], " else [ary, prefix] end end def encode(str, encoding) str.each_char.collect {|char| encoding[char]}.join end def decode(encoded, encoding) rev_enc = encoding.invert decoded = "" pos = 0 while pos < encoded.length key = "" while rev_enc[key].nil? key << encoded[pos] pos += 1 end decoded << rev_enc[key] end decoded end str = "this is an example for huffman encoding" encoding = huffman_encoding(str) encoding.to_a.sort.each {|x| p x} enc = encode(str, encoding) dec = decode(enc, encoding) puts "success!" if str == dec
#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 Ruby.
require 'priority_queue' def huffman_encoding(str) char_count = Hash.new(0) str.each_char {|c| char_count[c] += 1} pq = CPriorityQueue.new char_count.each {|char, count| pq.push(char, count)} while pq.length > 1 key1, prio1 = pq.delete_min key2, prio2 = pq.delete_min pq.push([key1, key2], prio1 + prio2) end Hash[*generate_encoding(pq.min_key)] end def generate_encoding(ary, prefix="") case ary when Array generate_encoding(ary[0], " else [ary, prefix] end end def encode(str, encoding) str.each_char.collect {|char| encoding[char]}.join end def decode(encoded, encoding) rev_enc = encoding.invert decoded = "" pos = 0 while pos < encoded.length key = "" while rev_enc[key].nil? key << encoded[pos] pos += 1 end decoded << rev_enc[key] end decoded end str = "this is an example for huffman encoding" encoding = huffman_encoding(str) encoding.to_a.sort.each {|x| p x} enc = encode(str, encoding) dec = decode(enc, encoding) puts "success!" if str == dec
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(); } } }
Keep all operations the same but rewrite the snippet in C++.
require 'priority_queue' def huffman_encoding(str) char_count = Hash.new(0) str.each_char {|c| char_count[c] += 1} pq = CPriorityQueue.new char_count.each {|char, count| pq.push(char, count)} while pq.length > 1 key1, prio1 = pq.delete_min key2, prio2 = pq.delete_min pq.push([key1, key2], prio1 + prio2) end Hash[*generate_encoding(pq.min_key)] end def generate_encoding(ary, prefix="") case ary when Array generate_encoding(ary[0], " else [ary, prefix] end end def encode(str, encoding) str.each_char.collect {|char| encoding[char]}.join end def decode(encoded, encoding) rev_enc = encoding.invert decoded = "" pos = 0 while pos < encoded.length key = "" while rev_enc[key].nil? key << encoded[pos] pos += 1 end decoded << rev_enc[key] end decoded end str = "this is an example for huffman encoding" encoding = huffman_encoding(str) encoding.to_a.sort.each {|x| p x} enc = encode(str, encoding) dec = decode(enc, encoding) puts "success!" if str == dec
#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 the given Ruby code snippet into Java without altering its behavior.
require 'priority_queue' def huffman_encoding(str) char_count = Hash.new(0) str.each_char {|c| char_count[c] += 1} pq = CPriorityQueue.new char_count.each {|char, count| pq.push(char, count)} while pq.length > 1 key1, prio1 = pq.delete_min key2, prio2 = pq.delete_min pq.push([key1, key2], prio1 + prio2) end Hash[*generate_encoding(pq.min_key)] end def generate_encoding(ary, prefix="") case ary when Array generate_encoding(ary[0], " else [ary, prefix] end end def encode(str, encoding) str.each_char.collect {|char| encoding[char]}.join end def decode(encoded, encoding) rev_enc = encoding.invert decoded = "" pos = 0 while pos < encoded.length key = "" while rev_enc[key].nil? key << encoded[pos] pos += 1 end decoded << rev_enc[key] end decoded end str = "this is an example for huffman encoding" encoding = huffman_encoding(str) encoding.to_a.sort.each {|x| p x} enc = encode(str, encoding) dec = decode(enc, encoding) puts "success!" if str == dec
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()); } }
Translate the given Ruby code snippet into Python without altering its behavior.
require 'priority_queue' def huffman_encoding(str) char_count = Hash.new(0) str.each_char {|c| char_count[c] += 1} pq = CPriorityQueue.new char_count.each {|char, count| pq.push(char, count)} while pq.length > 1 key1, prio1 = pq.delete_min key2, prio2 = pq.delete_min pq.push([key1, key2], prio1 + prio2) end Hash[*generate_encoding(pq.min_key)] end def generate_encoding(ary, prefix="") case ary when Array generate_encoding(ary[0], " else [ary, prefix] end end def encode(str, encoding) str.each_char.collect {|char| encoding[char]}.join end def decode(encoded, encoding) rev_enc = encoding.invert decoded = "" pos = 0 while pos < encoded.length key = "" while rev_enc[key].nil? key << encoded[pos] pos += 1 end decoded << rev_enc[key] end decoded end str = "this is an example for huffman encoding" encoding = huffman_encoding(str) encoding.to_a.sort.each {|x| p x} enc = encode(str, encoding) dec = decode(enc, encoding) puts "success!" if str == dec
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 Ruby block to Go, preserving its control flow and logic.
require 'priority_queue' def huffman_encoding(str) char_count = Hash.new(0) str.each_char {|c| char_count[c] += 1} pq = CPriorityQueue.new char_count.each {|char, count| pq.push(char, count)} while pq.length > 1 key1, prio1 = pq.delete_min key2, prio2 = pq.delete_min pq.push([key1, key2], prio1 + prio2) end Hash[*generate_encoding(pq.min_key)] end def generate_encoding(ary, prefix="") case ary when Array generate_encoding(ary[0], " else [ary, prefix] end end def encode(str, encoding) str.each_char.collect {|char| encoding[char]}.join end def decode(encoded, encoding) rev_enc = encoding.invert decoded = "" pos = 0 while pos < encoded.length key = "" while rev_enc[key].nil? key << encoded[pos] pos += 1 end decoded << rev_enc[key] end decoded end str = "this is an example for huffman encoding" encoding = huffman_encoding(str) encoding.to_a.sort.each {|x| p x} enc = encode(str, encoding) dec = decode(enc, encoding) puts "success!" if str == dec
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.
object Huffman { import scala.collection.mutable.{Map, PriorityQueue} sealed abstract class Tree case class Node(left: Tree, right: Tree) extends Tree case class Leaf(c: Char) extends Tree def treeOrdering(m: Map[Tree, Int]) = new Ordering[Tree] { def compare(x: Tree, y: Tree) = m(y).compare(m(x)) } def stringMap(text: String) = text groupBy (x => Leaf(x) : Tree) mapValues (_.length) def buildNode(queue: PriorityQueue[Tree], map: Map[Tree,Int]) { val right = queue.dequeue val left = queue.dequeue val node = Node(left, right) map(node) = map(left) + map(right) queue.enqueue(node) } def codify(tree: Tree, map: Map[Tree, Int]) = { def recurse(tree: Tree, prefix: String): List[(Char, (Int, String))] = tree match { case Node(left, right) => recurse(left, prefix+"0") ::: recurse(right, prefix+"1") case leaf @ Leaf(c) => c -> ((map(leaf), prefix)) :: Nil } recurse(tree, "") } def encode(text: String) = { val map = Map.empty[Tree,Int] ++= stringMap(text) val queue = new PriorityQueue[Tree]()(treeOrdering(map)) ++= map.keysIterator while(queue.size > 1) { buildNode(queue, map) } codify(queue.dequeue, map) } def main(args: Array[String]) { val text = "this is an example for huffman encoding" val code = encode(text) println("Char\tWeight\t\tEncoding") code sortBy (_._2._1) foreach { case (c, (weight, encoding)) => println("%c:\t%3d/%-3d\t\t%s" format (c, weight, text.length, encoding)) } } }
#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 Scala snippet.
object Huffman { import scala.collection.mutable.{Map, PriorityQueue} sealed abstract class Tree case class Node(left: Tree, right: Tree) extends Tree case class Leaf(c: Char) extends Tree def treeOrdering(m: Map[Tree, Int]) = new Ordering[Tree] { def compare(x: Tree, y: Tree) = m(y).compare(m(x)) } def stringMap(text: String) = text groupBy (x => Leaf(x) : Tree) mapValues (_.length) def buildNode(queue: PriorityQueue[Tree], map: Map[Tree,Int]) { val right = queue.dequeue val left = queue.dequeue val node = Node(left, right) map(node) = map(left) + map(right) queue.enqueue(node) } def codify(tree: Tree, map: Map[Tree, Int]) = { def recurse(tree: Tree, prefix: String): List[(Char, (Int, String))] = tree match { case Node(left, right) => recurse(left, prefix+"0") ::: recurse(right, prefix+"1") case leaf @ Leaf(c) => c -> ((map(leaf), prefix)) :: Nil } recurse(tree, "") } def encode(text: String) = { val map = Map.empty[Tree,Int] ++= stringMap(text) val queue = new PriorityQueue[Tree]()(treeOrdering(map)) ++= map.keysIterator while(queue.size > 1) { buildNode(queue, map) } codify(queue.dequeue, map) } def main(args: Array[String]) { val text = "this is an example for huffman encoding" val code = encode(text) println("Char\tWeight\t\tEncoding") code sortBy (_._2._1) foreach { case (c, (weight, encoding)) => println("%c:\t%3d/%-3d\t\t%s" format (c, weight, text.length, encoding)) } } }
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 Scala block to C++, preserving its control flow and logic.
object Huffman { import scala.collection.mutable.{Map, PriorityQueue} sealed abstract class Tree case class Node(left: Tree, right: Tree) extends Tree case class Leaf(c: Char) extends Tree def treeOrdering(m: Map[Tree, Int]) = new Ordering[Tree] { def compare(x: Tree, y: Tree) = m(y).compare(m(x)) } def stringMap(text: String) = text groupBy (x => Leaf(x) : Tree) mapValues (_.length) def buildNode(queue: PriorityQueue[Tree], map: Map[Tree,Int]) { val right = queue.dequeue val left = queue.dequeue val node = Node(left, right) map(node) = map(left) + map(right) queue.enqueue(node) } def codify(tree: Tree, map: Map[Tree, Int]) = { def recurse(tree: Tree, prefix: String): List[(Char, (Int, String))] = tree match { case Node(left, right) => recurse(left, prefix+"0") ::: recurse(right, prefix+"1") case leaf @ Leaf(c) => c -> ((map(leaf), prefix)) :: Nil } recurse(tree, "") } def encode(text: String) = { val map = Map.empty[Tree,Int] ++= stringMap(text) val queue = new PriorityQueue[Tree]()(treeOrdering(map)) ++= map.keysIterator while(queue.size > 1) { buildNode(queue, map) } codify(queue.dequeue, map) } def main(args: Array[String]) { val text = "this is an example for huffman encoding" val code = encode(text) println("Char\tWeight\t\tEncoding") code sortBy (_._2._1) foreach { case (c, (weight, encoding)) => println("%c:\t%3d/%-3d\t\t%s" format (c, weight, text.length, encoding)) } } }
#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 the following code from Scala to Java, ensuring the logic remains intact.
object Huffman { import scala.collection.mutable.{Map, PriorityQueue} sealed abstract class Tree case class Node(left: Tree, right: Tree) extends Tree case class Leaf(c: Char) extends Tree def treeOrdering(m: Map[Tree, Int]) = new Ordering[Tree] { def compare(x: Tree, y: Tree) = m(y).compare(m(x)) } def stringMap(text: String) = text groupBy (x => Leaf(x) : Tree) mapValues (_.length) def buildNode(queue: PriorityQueue[Tree], map: Map[Tree,Int]) { val right = queue.dequeue val left = queue.dequeue val node = Node(left, right) map(node) = map(left) + map(right) queue.enqueue(node) } def codify(tree: Tree, map: Map[Tree, Int]) = { def recurse(tree: Tree, prefix: String): List[(Char, (Int, String))] = tree match { case Node(left, right) => recurse(left, prefix+"0") ::: recurse(right, prefix+"1") case leaf @ Leaf(c) => c -> ((map(leaf), prefix)) :: Nil } recurse(tree, "") } def encode(text: String) = { val map = Map.empty[Tree,Int] ++= stringMap(text) val queue = new PriorityQueue[Tree]()(treeOrdering(map)) ++= map.keysIterator while(queue.size > 1) { buildNode(queue, map) } codify(queue.dequeue, map) } def main(args: Array[String]) { val text = "this is an example for huffman encoding" val code = encode(text) println("Char\tWeight\t\tEncoding") code sortBy (_._2._1) foreach { case (c, (weight, encoding)) => println("%c:\t%3d/%-3d\t\t%s" format (c, weight, text.length, encoding)) } } }
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 Scala to Python, same semantics.
object Huffman { import scala.collection.mutable.{Map, PriorityQueue} sealed abstract class Tree case class Node(left: Tree, right: Tree) extends Tree case class Leaf(c: Char) extends Tree def treeOrdering(m: Map[Tree, Int]) = new Ordering[Tree] { def compare(x: Tree, y: Tree) = m(y).compare(m(x)) } def stringMap(text: String) = text groupBy (x => Leaf(x) : Tree) mapValues (_.length) def buildNode(queue: PriorityQueue[Tree], map: Map[Tree,Int]) { val right = queue.dequeue val left = queue.dequeue val node = Node(left, right) map(node) = map(left) + map(right) queue.enqueue(node) } def codify(tree: Tree, map: Map[Tree, Int]) = { def recurse(tree: Tree, prefix: String): List[(Char, (Int, String))] = tree match { case Node(left, right) => recurse(left, prefix+"0") ::: recurse(right, prefix+"1") case leaf @ Leaf(c) => c -> ((map(leaf), prefix)) :: Nil } recurse(tree, "") } def encode(text: String) = { val map = Map.empty[Tree,Int] ++= stringMap(text) val queue = new PriorityQueue[Tree]()(treeOrdering(map)) ++= map.keysIterator while(queue.size > 1) { buildNode(queue, map) } codify(queue.dequeue, map) } def main(args: Array[String]) { val text = "this is an example for huffman encoding" val code = encode(text) println("Char\tWeight\t\tEncoding") code sortBy (_._2._1) foreach { case (c, (weight, encoding)) => println("%c:\t%3d/%-3d\t\t%s" format (c, weight, text.length, encoding)) } } }
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 language-to-language conversion: from Scala to Go, same semantics.
object Huffman { import scala.collection.mutable.{Map, PriorityQueue} sealed abstract class Tree case class Node(left: Tree, right: Tree) extends Tree case class Leaf(c: Char) extends Tree def treeOrdering(m: Map[Tree, Int]) = new Ordering[Tree] { def compare(x: Tree, y: Tree) = m(y).compare(m(x)) } def stringMap(text: String) = text groupBy (x => Leaf(x) : Tree) mapValues (_.length) def buildNode(queue: PriorityQueue[Tree], map: Map[Tree,Int]) { val right = queue.dequeue val left = queue.dequeue val node = Node(left, right) map(node) = map(left) + map(right) queue.enqueue(node) } def codify(tree: Tree, map: Map[Tree, Int]) = { def recurse(tree: Tree, prefix: String): List[(Char, (Int, String))] = tree match { case Node(left, right) => recurse(left, prefix+"0") ::: recurse(right, prefix+"1") case leaf @ Leaf(c) => c -> ((map(leaf), prefix)) :: Nil } recurse(tree, "") } def encode(text: String) = { val map = Map.empty[Tree,Int] ++= stringMap(text) val queue = new PriorityQueue[Tree]()(treeOrdering(map)) ++= map.keysIterator while(queue.size > 1) { buildNode(queue, map) } codify(queue.dequeue, map) } def main(args: Array[String]) { val text = "this is an example for huffman encoding" val code = encode(text) println("Char\tWeight\t\tEncoding") code sortBy (_._2._1) foreach { case (c, (weight, encoding)) => println("%c:\t%3d/%-3d\t\t%s" format (c, weight, text.length, encoding)) } } }
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 a C translation of this Swift snippet without changing its computational steps.
enum HuffmanTree<T> { case Leaf(T) indirect case Node(HuffmanTree<T>, HuffmanTree<T>) func printCodes(prefix: String) { switch(self) { case let .Leaf(c): print("\(c)\t\(prefix)") case let .Node(l, r): l.printCodes(prefix + "0") r.printCodes(prefix + "1") } } } func buildTree<T>(freqs: [(T, Int)]) -> HuffmanTree<T> { assert(freqs.count > 0, "must contain at least one character") let leaves : [(Int, HuffmanTree<T>)] = freqs.sort { (p1, p2) in p1.1 < p2.1 }.map { (x, w) in (w, .Leaf(x)) } var nodes = [(Int, HuffmanTree<T>)]() for var i = 0, j = 0; ; { assert(i < leaves.count || j < nodes.count) var e1 : (Int, HuffmanTree<T>) if j == nodes.count || i < leaves.count && leaves[i].0 < nodes[j].0 { e1 = leaves[i] i++ } else { e1 = nodes[j] j++ } if i == leaves.count && j == nodes.count { return e1.1 } var e2 : (Int, HuffmanTree<T>) if j == nodes.count || i < leaves.count && leaves[i].0 < nodes[j].0 { e2 = leaves[i] i++ } else { e2 = nodes[j] j++ } nodes.append((e1.0 + e2.0, .Node(e1.1, e2.1))) } } func getFreqs<S : SequenceType where S.Generator.Element : Hashable>(seq: S) -> [(S.Generator.Element, Int)] { var freqs : [S.Generator.Element : Int] = [:] for c in seq { freqs[c] = (freqs[c] ?? 0) + 1 } return Array(freqs) } let str = "this is an example for huffman encoding" let charFreqs = getFreqs(str.characters) let tree = buildTree(charFreqs) print("Symbol\tHuffman code") tree.printCodes("")
#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 Swift to C#, ensuring the logic remains intact.
enum HuffmanTree<T> { case Leaf(T) indirect case Node(HuffmanTree<T>, HuffmanTree<T>) func printCodes(prefix: String) { switch(self) { case let .Leaf(c): print("\(c)\t\(prefix)") case let .Node(l, r): l.printCodes(prefix + "0") r.printCodes(prefix + "1") } } } func buildTree<T>(freqs: [(T, Int)]) -> HuffmanTree<T> { assert(freqs.count > 0, "must contain at least one character") let leaves : [(Int, HuffmanTree<T>)] = freqs.sort { (p1, p2) in p1.1 < p2.1 }.map { (x, w) in (w, .Leaf(x)) } var nodes = [(Int, HuffmanTree<T>)]() for var i = 0, j = 0; ; { assert(i < leaves.count || j < nodes.count) var e1 : (Int, HuffmanTree<T>) if j == nodes.count || i < leaves.count && leaves[i].0 < nodes[j].0 { e1 = leaves[i] i++ } else { e1 = nodes[j] j++ } if i == leaves.count && j == nodes.count { return e1.1 } var e2 : (Int, HuffmanTree<T>) if j == nodes.count || i < leaves.count && leaves[i].0 < nodes[j].0 { e2 = leaves[i] i++ } else { e2 = nodes[j] j++ } nodes.append((e1.0 + e2.0, .Node(e1.1, e2.1))) } } func getFreqs<S : SequenceType where S.Generator.Element : Hashable>(seq: S) -> [(S.Generator.Element, Int)] { var freqs : [S.Generator.Element : Int] = [:] for c in seq { freqs[c] = (freqs[c] ?? 0) + 1 } return Array(freqs) } let str = "this is an example for huffman encoding" let charFreqs = getFreqs(str.characters) let tree = buildTree(charFreqs) print("Symbol\tHuffman code") tree.printCodes("")
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 Swift snippet.
enum HuffmanTree<T> { case Leaf(T) indirect case Node(HuffmanTree<T>, HuffmanTree<T>) func printCodes(prefix: String) { switch(self) { case let .Leaf(c): print("\(c)\t\(prefix)") case let .Node(l, r): l.printCodes(prefix + "0") r.printCodes(prefix + "1") } } } func buildTree<T>(freqs: [(T, Int)]) -> HuffmanTree<T> { assert(freqs.count > 0, "must contain at least one character") let leaves : [(Int, HuffmanTree<T>)] = freqs.sort { (p1, p2) in p1.1 < p2.1 }.map { (x, w) in (w, .Leaf(x)) } var nodes = [(Int, HuffmanTree<T>)]() for var i = 0, j = 0; ; { assert(i < leaves.count || j < nodes.count) var e1 : (Int, HuffmanTree<T>) if j == nodes.count || i < leaves.count && leaves[i].0 < nodes[j].0 { e1 = leaves[i] i++ } else { e1 = nodes[j] j++ } if i == leaves.count && j == nodes.count { return e1.1 } var e2 : (Int, HuffmanTree<T>) if j == nodes.count || i < leaves.count && leaves[i].0 < nodes[j].0 { e2 = leaves[i] i++ } else { e2 = nodes[j] j++ } nodes.append((e1.0 + e2.0, .Node(e1.1, e2.1))) } } func getFreqs<S : SequenceType where S.Generator.Element : Hashable>(seq: S) -> [(S.Generator.Element, Int)] { var freqs : [S.Generator.Element : Int] = [:] for c in seq { freqs[c] = (freqs[c] ?? 0) + 1 } return Array(freqs) } let str = "this is an example for huffman encoding" let charFreqs = getFreqs(str.characters) let tree = buildTree(charFreqs) print("Symbol\tHuffman code") tree.printCodes("")
#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 Swift code.
enum HuffmanTree<T> { case Leaf(T) indirect case Node(HuffmanTree<T>, HuffmanTree<T>) func printCodes(prefix: String) { switch(self) { case let .Leaf(c): print("\(c)\t\(prefix)") case let .Node(l, r): l.printCodes(prefix + "0") r.printCodes(prefix + "1") } } } func buildTree<T>(freqs: [(T, Int)]) -> HuffmanTree<T> { assert(freqs.count > 0, "must contain at least one character") let leaves : [(Int, HuffmanTree<T>)] = freqs.sort { (p1, p2) in p1.1 < p2.1 }.map { (x, w) in (w, .Leaf(x)) } var nodes = [(Int, HuffmanTree<T>)]() for var i = 0, j = 0; ; { assert(i < leaves.count || j < nodes.count) var e1 : (Int, HuffmanTree<T>) if j == nodes.count || i < leaves.count && leaves[i].0 < nodes[j].0 { e1 = leaves[i] i++ } else { e1 = nodes[j] j++ } if i == leaves.count && j == nodes.count { return e1.1 } var e2 : (Int, HuffmanTree<T>) if j == nodes.count || i < leaves.count && leaves[i].0 < nodes[j].0 { e2 = leaves[i] i++ } else { e2 = nodes[j] j++ } nodes.append((e1.0 + e2.0, .Node(e1.1, e2.1))) } } func getFreqs<S : SequenceType where S.Generator.Element : Hashable>(seq: S) -> [(S.Generator.Element, Int)] { var freqs : [S.Generator.Element : Int] = [:] for c in seq { freqs[c] = (freqs[c] ?? 0) + 1 } return Array(freqs) } let str = "this is an example for huffman encoding" let charFreqs = getFreqs(str.characters) let tree = buildTree(charFreqs) print("Symbol\tHuffman code") tree.printCodes("")
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()); } }
Rewrite this program in Python while keeping its functionality equivalent to the Swift version.
enum HuffmanTree<T> { case Leaf(T) indirect case Node(HuffmanTree<T>, HuffmanTree<T>) func printCodes(prefix: String) { switch(self) { case let .Leaf(c): print("\(c)\t\(prefix)") case let .Node(l, r): l.printCodes(prefix + "0") r.printCodes(prefix + "1") } } } func buildTree<T>(freqs: [(T, Int)]) -> HuffmanTree<T> { assert(freqs.count > 0, "must contain at least one character") let leaves : [(Int, HuffmanTree<T>)] = freqs.sort { (p1, p2) in p1.1 < p2.1 }.map { (x, w) in (w, .Leaf(x)) } var nodes = [(Int, HuffmanTree<T>)]() for var i = 0, j = 0; ; { assert(i < leaves.count || j < nodes.count) var e1 : (Int, HuffmanTree<T>) if j == nodes.count || i < leaves.count && leaves[i].0 < nodes[j].0 { e1 = leaves[i] i++ } else { e1 = nodes[j] j++ } if i == leaves.count && j == nodes.count { return e1.1 } var e2 : (Int, HuffmanTree<T>) if j == nodes.count || i < leaves.count && leaves[i].0 < nodes[j].0 { e2 = leaves[i] i++ } else { e2 = nodes[j] j++ } nodes.append((e1.0 + e2.0, .Node(e1.1, e2.1))) } } func getFreqs<S : SequenceType where S.Generator.Element : Hashable>(seq: S) -> [(S.Generator.Element, Int)] { var freqs : [S.Generator.Element : Int] = [:] for c in seq { freqs[c] = (freqs[c] ?? 0) + 1 } return Array(freqs) } let str = "this is an example for huffman encoding" let charFreqs = getFreqs(str.characters) let tree = buildTree(charFreqs) print("Symbol\tHuffman code") tree.printCodes("")
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 Swift code into Go while preserving the original functionality.
enum HuffmanTree<T> { case Leaf(T) indirect case Node(HuffmanTree<T>, HuffmanTree<T>) func printCodes(prefix: String) { switch(self) { case let .Leaf(c): print("\(c)\t\(prefix)") case let .Node(l, r): l.printCodes(prefix + "0") r.printCodes(prefix + "1") } } } func buildTree<T>(freqs: [(T, Int)]) -> HuffmanTree<T> { assert(freqs.count > 0, "must contain at least one character") let leaves : [(Int, HuffmanTree<T>)] = freqs.sort { (p1, p2) in p1.1 < p2.1 }.map { (x, w) in (w, .Leaf(x)) } var nodes = [(Int, HuffmanTree<T>)]() for var i = 0, j = 0; ; { assert(i < leaves.count || j < nodes.count) var e1 : (Int, HuffmanTree<T>) if j == nodes.count || i < leaves.count && leaves[i].0 < nodes[j].0 { e1 = leaves[i] i++ } else { e1 = nodes[j] j++ } if i == leaves.count && j == nodes.count { return e1.1 } var e2 : (Int, HuffmanTree<T>) if j == nodes.count || i < leaves.count && leaves[i].0 < nodes[j].0 { e2 = leaves[i] i++ } else { e2 = nodes[j] j++ } nodes.append((e1.0 + e2.0, .Node(e1.1, e2.1))) } } func getFreqs<S : SequenceType where S.Generator.Element : Hashable>(seq: S) -> [(S.Generator.Element, Int)] { var freqs : [S.Generator.Element : Int] = [:] for c in seq { freqs[c] = (freqs[c] ?? 0) + 1 } return Array(freqs) } let str = "this is an example for huffman encoding" let charFreqs = getFreqs(str.characters) let tree = buildTree(charFreqs) print("Symbol\tHuffman code") tree.printCodes("")
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 Tcl.
package require Tcl 8.5 package require struct::prioqueue proc huffmanEncode {str args} { array set opts [concat -dump false $args] set charcount [dict create] foreach char [split $str ""] { dict incr charcount $char } set pq [struct::prioqueue -dictionary] ; dict for {char count} $charcount { $pq put $char $count } while {[$pq size] > 1} { lassign [$pq peekpriority 2] p1 p2 $pq put [$pq get 2] [expr {$p1 + $p2}] } set encoding [walkTree [$pq get]] if {$opts(-dump)} { foreach {char huffCode} [lsort -index 1 -stride 2 -command compare $encoding] { puts "$char\t[dict get $charcount $char]\t$huffCode" } } $pq destroy return $encoding } proc walkTree {tree {prefix ""}} { if {[llength $tree] < 2} { return [list $tree $prefix] } lassign $tree left right return [concat [walkTree $left "${prefix}0"] [walkTree $right "${prefix}1"]] } proc compare {a b} { if {[string length $a] < [string length $b]} {return -1} if {[string length $a] > [string length $b]} {return 1} return [string compare $a $b] } set str "this is an example for huffman encoding" set encoding [huffmanEncode $str -dump true] puts $str puts [string map $encoding $str]
#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; }
Translate the given Tcl code snippet into C# without altering its behavior.
package require Tcl 8.5 package require struct::prioqueue proc huffmanEncode {str args} { array set opts [concat -dump false $args] set charcount [dict create] foreach char [split $str ""] { dict incr charcount $char } set pq [struct::prioqueue -dictionary] ; dict for {char count} $charcount { $pq put $char $count } while {[$pq size] > 1} { lassign [$pq peekpriority 2] p1 p2 $pq put [$pq get 2] [expr {$p1 + $p2}] } set encoding [walkTree [$pq get]] if {$opts(-dump)} { foreach {char huffCode} [lsort -index 1 -stride 2 -command compare $encoding] { puts "$char\t[dict get $charcount $char]\t$huffCode" } } $pq destroy return $encoding } proc walkTree {tree {prefix ""}} { if {[llength $tree] < 2} { return [list $tree $prefix] } lassign $tree left right return [concat [walkTree $left "${prefix}0"] [walkTree $right "${prefix}1"]] } proc compare {a b} { if {[string length $a] < [string length $b]} {return -1} if {[string length $a] > [string length $b]} {return 1} return [string compare $a $b] } set str "this is an example for huffman encoding" set encoding [huffmanEncode $str -dump true] puts $str puts [string map $encoding $str]
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 Tcl to C++, same semantics.
package require Tcl 8.5 package require struct::prioqueue proc huffmanEncode {str args} { array set opts [concat -dump false $args] set charcount [dict create] foreach char [split $str ""] { dict incr charcount $char } set pq [struct::prioqueue -dictionary] ; dict for {char count} $charcount { $pq put $char $count } while {[$pq size] > 1} { lassign [$pq peekpriority 2] p1 p2 $pq put [$pq get 2] [expr {$p1 + $p2}] } set encoding [walkTree [$pq get]] if {$opts(-dump)} { foreach {char huffCode} [lsort -index 1 -stride 2 -command compare $encoding] { puts "$char\t[dict get $charcount $char]\t$huffCode" } } $pq destroy return $encoding } proc walkTree {tree {prefix ""}} { if {[llength $tree] < 2} { return [list $tree $prefix] } lassign $tree left right return [concat [walkTree $left "${prefix}0"] [walkTree $right "${prefix}1"]] } proc compare {a b} { if {[string length $a] < [string length $b]} {return -1} if {[string length $a] > [string length $b]} {return 1} return [string compare $a $b] } set str "this is an example for huffman encoding" set encoding [huffmanEncode $str -dump true] puts $str puts [string map $encoding $str]
#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 functionally identical Java code for the snippet given in Tcl.
package require Tcl 8.5 package require struct::prioqueue proc huffmanEncode {str args} { array set opts [concat -dump false $args] set charcount [dict create] foreach char [split $str ""] { dict incr charcount $char } set pq [struct::prioqueue -dictionary] ; dict for {char count} $charcount { $pq put $char $count } while {[$pq size] > 1} { lassign [$pq peekpriority 2] p1 p2 $pq put [$pq get 2] [expr {$p1 + $p2}] } set encoding [walkTree [$pq get]] if {$opts(-dump)} { foreach {char huffCode} [lsort -index 1 -stride 2 -command compare $encoding] { puts "$char\t[dict get $charcount $char]\t$huffCode" } } $pq destroy return $encoding } proc walkTree {tree {prefix ""}} { if {[llength $tree] < 2} { return [list $tree $prefix] } lassign $tree left right return [concat [walkTree $left "${prefix}0"] [walkTree $right "${prefix}1"]] } proc compare {a b} { if {[string length $a] < [string length $b]} {return -1} if {[string length $a] > [string length $b]} {return 1} return [string compare $a $b] } set str "this is an example for huffman encoding" set encoding [huffmanEncode $str -dump true] puts $str puts [string map $encoding $str]
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()); } }
Keep all operations the same but rewrite the snippet in Python.
package require Tcl 8.5 package require struct::prioqueue proc huffmanEncode {str args} { array set opts [concat -dump false $args] set charcount [dict create] foreach char [split $str ""] { dict incr charcount $char } set pq [struct::prioqueue -dictionary] ; dict for {char count} $charcount { $pq put $char $count } while {[$pq size] > 1} { lassign [$pq peekpriority 2] p1 p2 $pq put [$pq get 2] [expr {$p1 + $p2}] } set encoding [walkTree [$pq get]] if {$opts(-dump)} { foreach {char huffCode} [lsort -index 1 -stride 2 -command compare $encoding] { puts "$char\t[dict get $charcount $char]\t$huffCode" } } $pq destroy return $encoding } proc walkTree {tree {prefix ""}} { if {[llength $tree] < 2} { return [list $tree $prefix] } lassign $tree left right return [concat [walkTree $left "${prefix}0"] [walkTree $right "${prefix}1"]] } proc compare {a b} { if {[string length $a] < [string length $b]} {return -1} if {[string length $a] > [string length $b]} {return 1} return [string compare $a $b] } set str "this is an example for huffman encoding" set encoding [huffmanEncode $str -dump true] puts $str puts [string map $encoding $str]
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 Tcl, keeping it the same logically?
package require Tcl 8.5 package require struct::prioqueue proc huffmanEncode {str args} { array set opts [concat -dump false $args] set charcount [dict create] foreach char [split $str ""] { dict incr charcount $char } set pq [struct::prioqueue -dictionary] ; dict for {char count} $charcount { $pq put $char $count } while {[$pq size] > 1} { lassign [$pq peekpriority 2] p1 p2 $pq put [$pq get 2] [expr {$p1 + $p2}] } set encoding [walkTree [$pq get]] if {$opts(-dump)} { foreach {char huffCode} [lsort -index 1 -stride 2 -command compare $encoding] { puts "$char\t[dict get $charcount $char]\t$huffCode" } } $pq destroy return $encoding } proc walkTree {tree {prefix ""}} { if {[llength $tree] < 2} { return [list $tree $prefix] } lassign $tree left right return [concat [walkTree $left "${prefix}0"] [walkTree $right "${prefix}1"]] } proc compare {a b} { if {[string length $a] < [string length $b]} {return -1} if {[string length $a] > [string length $b]} {return 1} return [string compare $a $b] } set str "this is an example for huffman encoding" set encoding [huffmanEncode $str -dump true] puts $str puts [string map $encoding $str]
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 Rust snippet to PHP and keep its semantics consistent.
use std::collections::BTreeMap; use std::collections::binary_heap::BinaryHeap; #[derive(Debug, Eq, PartialEq)] enum NodeKind { Internal(Box<Node>, Box<Node>), Leaf(char), } #[derive(Debug, Eq, PartialEq)] struct Node { frequency: usize, kind: NodeKind, } impl Ord for Node { fn cmp(&self, rhs: &Self) -> std::cmp::Ordering { rhs.frequency.cmp(&self.frequency) } } impl PartialOrd for Node { fn partial_cmp(&self, rhs: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(&rhs)) } } type HuffmanCodeMap = BTreeMap<char, Vec<u8>>; fn main() { let text = "this is an example for huffman encoding"; let mut frequencies = BTreeMap::new(); for ch in text.chars() { *frequencies.entry(ch).or_insert(0) += 1; } let mut prioritized_frequencies = BinaryHeap::new(); for counted_char in frequencies { prioritized_frequencies.push(Node { frequency: counted_char.1, kind: NodeKind::Leaf(counted_char.0), }); } while prioritized_frequencies.len() > 1 { let left_child = prioritized_frequencies.pop().unwrap(); let right_child = prioritized_frequencies.pop().unwrap(); prioritized_frequencies.push(Node { frequency: right_child.frequency + left_child.frequency, kind: NodeKind::Internal(Box::new(left_child), Box::new(right_child)), }); } let mut codes = HuffmanCodeMap::new(); generate_codes( prioritized_frequencies.peek().unwrap(), vec![0u8; 0], &mut codes, ); for item in codes { print!("{}: ", item.0); for bit in item.1 { print!("{}", bit); } println!(); } } fn generate_codes(node: &Node, prefix: Vec<u8>, out_codes: &mut HuffmanCodeMap) { match node.kind { NodeKind::Internal(ref left_child, ref right_child) => { let mut left_prefix = prefix.clone(); left_prefix.push(0); generate_codes(&left_child, left_prefix, out_codes); let mut right_prefix = prefix; right_prefix.push(1); generate_codes(&right_child, right_prefix, out_codes); } NodeKind::Leaf(ch) => { out_codes.insert(ch, prefix); } } }
<?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"; ?>
Change the programming language of this snippet from Ada to PHP without modifying what it does.
with Ada.Containers.Indefinite_Ordered_Maps; with Ada.Containers.Ordered_Maps; with Ada.Finalization; generic type Symbol_Type is private; with function "<" (Left, Right : Symbol_Type) return Boolean is <>; with procedure Put (Item : Symbol_Type); type Symbol_Sequence is array (Positive range <>) of Symbol_Type; type Frequency_Type is private; with function "+" (Left, Right : Frequency_Type) return Frequency_Type is <>; with function "<" (Left, Right : Frequency_Type) return Boolean is <>; package Huffman is type Bit_Sequence is array (Positive range <>) of Boolean; Zero_Sequence : constant Bit_Sequence (1 .. 0) := (others => False); procedure Put (Code : Bit_Sequence); package Frequency_Maps is new Ada.Containers.Ordered_Maps (Element_Type => Frequency_Type, Key_Type => Symbol_Type); type Huffman_Tree is private; procedure Create_Tree (Tree : out Huffman_Tree; Frequencies : Frequency_Maps.Map); function Encode (Tree : Huffman_Tree; Symbol : Symbol_Type) return Bit_Sequence; function Encode (Tree : Huffman_Tree; Symbols : Symbol_Sequence) return Bit_Sequence; function Decode (Tree : Huffman_Tree; Code : Bit_Sequence) return Symbol_Sequence; procedure Dump_Encoding (Tree : Huffman_Tree); private package Encoding_Maps is new Ada.Containers.Indefinite_Ordered_Maps (Element_Type => Bit_Sequence, Key_Type => Symbol_Type); type Huffman_Node; type Node_Access is access Huffman_Node; type Huffman_Node is record Frequency : Frequency_Type; Left_Child : Node_Access := null; Right_Child : Node_Access := null; Symbol : Symbol_Type; end record; function Create_Node (Symbol : Symbol_Type; Frequency : Frequency_Type) return Node_Access; function Create_Node (Left, Right : Node_Access) return Node_Access; procedure Fill (The_Node : Node_Access; Map : in out Encoding_Maps.Map; Prefix : Bit_Sequence); type Huffman_Tree is new Ada.Finalization.Controlled with record Tree : Node_Access := null; Map : Encoding_Maps.Map := Encoding_Maps.Empty_Map; end record; overriding procedure Finalize (Object : in out Huffman_Tree); end Huffman;
<?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"; ?>
Transform the following BBC_Basic implementation into PHP, maintaining the same output 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
<?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"; ?>
Convert this Clojure block to PHP, preserving its control flow 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")
<?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"; ?>
Change the programming language of this snippet from Common_Lisp to PHP without modifying what it does.
(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))))
<?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"; ?>
Convert the following code from D to PHP, ensuring the logic remains intact.
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[]); }
<?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"; ?>
Preserve the algorithm and functionality while converting the code from Erlang to PHP.
-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).
<?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"; ?>
Transform the following F# implementation into PHP, maintaining the same output and logic.
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)
<?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"; ?>
Convert this Factor snippet to PHP and keep its semantics consistent.
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 ;
<?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"; ?>
Produce a language-to-language conversion: from Fortran to PHP, same semantics.
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"; ?>
Write the same algorithm in PHP as shown in this Groovy implementation.
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 }
<?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"; ?>
Rewrite this program in PHP while keeping its functionality equivalent to the Haskell version.
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"
<?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"; ?>
Generate a PHP translation of this Icon snippet without changing its computational steps.
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
<?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"; ?>
Write a version of this J function in PHP with identical behavior.
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 )
<?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"; ?>
Convert this Julia block to PHP, 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)), "")
<?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"; ?>
Generate a PHP translation of this Lua snippet without changing its computational steps.
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"
<?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"; ?>
Change the programming language of this snippet from Mathematica to PHP without modifying what it does.
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}];
<?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"; ?>
Generate an equivalent PHP 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}"
<?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"; ?>
Port the provided OCaml code into PHP while preserving the original functionality.
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
<?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"; ?>
Ensure the translated PHP code behaves exactly like the original Perl snippet.
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";
<?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"; ?>
Can you help me rewrite this code in PHP instead of PowerShell, keeping it the same logically?
function Get-HuffmanEncodingTable ( $String ) { $ID = 0 $Nodes = [char[]]$String | Group-Object | ForEach { $ID++; $_ } | Select @{ Label = 'Symbol' ; Expression = { $_.Name } }, @{ Label = 'Count' ; Expression = { $_.Count } }, @{ Label = 'ID' ; Expression = { $ID } }, @{ Label = 'Parent' ; Expression = { 0 } }, @{ Label = 'Code' ; Expression = { '' } } ForEach ( $Branch in 2..($Nodes.Count) ) { $LowNodes = $Nodes | Where Parent -eq 0 | Sort Count | Select -First 2 $ID++ $Nodes += '' | Select @{ Label = 'Symbol' ; Expression = { '' } }, @{ Label = 'Count' ; Expression = { $LowNodes[0].Count + $LowNodes[1].Count } }, @{ Label = 'ID' ; Expression = { $ID } }, @{ Label = 'Parent' ; Expression = { 0 } }, @{ Label = 'Code' ; Expression = { '' } } $LowNodes[0].Parent = $ID $LowNodes[1].Parent = $ID $LowNodes[0].Code = '0' $LowNodes[1].Code = '1' } ForEach ( $Node in $Nodes[($Nodes.Count-2)..0] ) { $Node.Code = ( $Nodes | Where ID -eq $Node.Parent ).Code + $Node.Code } $EncodingTable = $Nodes | Where { $_.Symbol } | Select Symbol, Code | Sort Symbol return $EncodingTable } $String = "this is an example for huffman encoding" $HuffmanEncodingTable = Get-HuffmanEncodingTable $String $HuffmanEncodingTable | Format-Table -AutoSize $EncodedString = $String ForEach ( $Node in $HuffmanEncodingTable ) { $EncodedString = $EncodedString.Replace( $Node.Symbol, $Node.Code ) } $EncodedString
<?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 Racket code in PHP.
#lang racket (require data/heap data/bit-vector) (struct node (freq) #:transparent) (struct interior node (left right) #:transparent) (struct leaf node (val) #:transparent) (define (node<=? x y) (<= (node-freq x) (node-freq y))) (define (make-huffman-tree leaves) (define a-heap (make-heap node<=?)) (heap-add-all! a-heap leaves) (for ([i (sub1 (length leaves))]) (define min-1 (heap-min a-heap)) (heap-remove-min! a-heap) (define min-2 (heap-min a-heap)) (heap-remove-min! a-heap) (heap-add! a-heap (interior (+ (node-freq min-1) (node-freq min-2)) min-1 min-2))) (heap-min a-heap)) (define (string->huffman-tree str) (define ht (make-hash)) (define n (sequence-length str)) (for ([ch str]) (hash-update! ht ch add1 (λ () 0))) (make-huffman-tree (for/list ([(k v) (in-hash ht)]) (leaf (/ v n) k)))) (define (make-encoder a-tree) (define dict (huffman-tree->dictionary a-tree)) (lambda (a-str) (list->bit-vector (apply append (for/list ([ch a-str]) (hash-ref dict ch)))))) (define (huffman-tree->dictionary a-node) (define ht (make-hash)) (let loop ([a-node a-node] [path/rev '()]) (cond [(interior? a-node) (loop (interior-left a-node) (cons #f path/rev)) (loop (interior-right a-node) (cons #t path/rev))] [(leaf? a-node) (hash-set! ht (reverse path/rev) (leaf-val a-node))])) (for/hash ([(k v) ht]) (values v k))) (define (make-decoder a-tree) (lambda (a-bitvector) (define-values (decoded/rev _) (for/fold ([decoded/rev '()] [a-node a-tree]) ([bit a-bitvector]) (define next-node (cond [(not bit) (interior-left a-node)] [else (interior-right a-node)])) (cond [(leaf? next-node) (values (cons (leaf-val next-node) decoded/rev) a-tree)] [else (values decoded/rev next-node)]))) (apply string (reverse decoded/rev)))) (define msg "this is an example for huffman encoding") (define tree (string->huffman-tree msg)) (huffman-tree->dictionary tree) (define encode (make-encoder tree)) (define encoded (encode msg)) (bit-vector->string encoded) (define decode (make-decoder tree)) (decode encoded)
<?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"; ?>
Convert this REXX snippet to PHP and keep its semantics consistent.
* 27.12.2013 Walter Pachl * 29.12.2013 -"- changed for test of s=xrange('00'x,'ff'x) * 14.03.2018 -"- use format instead of right to diagnose size poblems * Stem m contains eventually the following node data * m.i.0id Node id * m.i.0c character * m.i.0o number of occurrences * m.i.0l left child * m.i.0r right child * m.i.0f father * m.i.0d digit (0 or 1) * m.i.0t 1=a terminal node 0=an intermediate or the top node *--------------------------------------------------------------------*/ Parse Arg s If s='' Then s='this is an example for huffman encoding' Say 'We encode this string:' Say s debug=0 o.=0 c.=0 codel.=0 code.='' father.=0 cl='' do i=1 To length(s) Call memorize substr(s,i,1) End If debug Then Do Do i=1 To c.0 c=c.i Say i c o.c End End n.=0 Do i=1 To c.0 c=c.i n.i.0c=c n.i.0o=o.c n.i.0id=i Call dbg i n.i.0id n.i.0c n.i.0o End n=c.0 m.=0 Do i=1 To n Do j=1 To m.0 If m.j.0o>n.i.0o Then Leave End Do k=m.0 To j By -1 k1=k+1 m.k1.0id=m.k.0id m.k1.0c =m.k.0c m.k1.0o =m.k.0o m.k1.0t =m.k.0t End m.j.0id=i m.j.0c =n.i.0c m.j.0o =n.i.0o m.j.0t =1 m.0=m.0+1 End If debug Then Call show Do While pairs()>1 Call mknode If debug Then Call show End Call show c.=0 Do i=1 To m.0 If m.i.0t Then Do code=m.i.0d node=m.i.0id Do fi=1 To 1000 fid=father.node If fid<>0 Then Do fidz=zeile(fid) code=m.fidz.0d||code node=fid End Else Leave End If length(code)>1 Then code=substr(code,2) call dbg m.i.0c '->' code char=m.i.0c code.char=code z=codel.0+1 codel.z=code codel.0=z char.code=char End End Call show_char2code codes.=0 Do j=1 To codel.0 z=codes.0+1 code=codel.j codes.z=code chars.z=char.code codes.0=z Call dbg codes.z '----->' chars.z End sc='' Do i=1 To length(s) c=substr(s,i,1) sc=sc||code.c End Say 'Length of encoded string:' length(sc) Do i=1 To length(sc) by 70 Say substr(sc,i,70) End sr='' Do si=1 To 999 While sc<>'' Do i=codes.0 To 1 By -1 cl=length(codes.i) If left(sc,cl)==codes.i Then Do sr=sr||chars.i sc=substr(sc,cl+1) Leave End End End Say 'Input ="'s'"' Say 'result="'sr'"' Exit show: * show all lines representing node data *--------------------------------------------------------------------*/ Say ' i pp id c f l r d' Do i=1 To m.0 Say format(i,3) format(m.i.0o,4) format(m.i.0id,3), format(m.i.0f,3) format(m.i.0l,3) format(m.i.0r,3) m.i.0d m.i.0t End Call dbg copies('-',21) Return pairs: Procedure Expose m. * return number of fatherless nodes *--------------------------------------------------------------------*/ res=0 Do i=1 To m.0 If m.i.0f=0 Then res=res+1 End Return res mknode: * construct and store a new intermediate or the top node *--------------------------------------------------------------------*/ new.=0 ni=m.0+1 Do i=1 To m.0 If m.i.0f=0 Then Do z=m.i.0id If new.0l=0 Then Do new.0l=z new.0o=m.i.0o m.i.0f=ni m.i.0d='0' father.z=ni End Else Do new.0r=z new.0o=new.0o+m.i.0o m.i.0f=ni m.i.0d=1 father.z=ni Leave End End End Do i=1 To m.0 If m.i.0o>=new.0o Then Do Do k=m.0 To i By -1 k1=k+1 m.k1.0id=m.k.0id m.k1.0o =m.k.0o m.k1.0c =m.k.0c m.k1.0l =m.k.0l m.k1.0r =m.k.0r m.k1.0f =m.k.0f m.k1.0d =m.k.0d m.k1.0t =m.k.0t End Leave End End m.i.0id=ni m.i.0c ='*' m.i.0o =new.0o m.i.0l =new.0l m.i.0r =new.0r m.i.0t =0 father.ni=0 m.0=ni Return zeile: * find and return line number containing node-id *--------------------------------------------------------------------*/ do fidz=1 To m.0 If m.fidz.0id=arg(1) Then Return fidz End Call dbg arg(1) 'not found' Pull . dbg: * Show text if debug is enabled *--------------------------------------------------------------------*/ If debug=1 Then Say arg(1) Return memorize: Procedure Expose c. o. * store characters and corresponding occurrences *--------------------------------------------------------------------*/ Parse Arg c If o.c=0 Then Do z=c.0+1 c.z=c c.0=z End o.c=o.c+1 Return show_char2code: * show used characters and corresponding codes *--------------------------------------------------------------------*/ cl=xrange('00'x,'ff'x) Say 'char --> code' Do While cl<>'' Parse Var cl c +1 cl If code.c<>'' Then Say ' 'c '-->' code.c End Return
<?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"; ?>
Convert this Ruby block to PHP, preserving its control flow and logic.
require 'priority_queue' def huffman_encoding(str) char_count = Hash.new(0) str.each_char {|c| char_count[c] += 1} pq = CPriorityQueue.new char_count.each {|char, count| pq.push(char, count)} while pq.length > 1 key1, prio1 = pq.delete_min key2, prio2 = pq.delete_min pq.push([key1, key2], prio1 + prio2) end Hash[*generate_encoding(pq.min_key)] end def generate_encoding(ary, prefix="") case ary when Array generate_encoding(ary[0], " else [ary, prefix] end end def encode(str, encoding) str.each_char.collect {|char| encoding[char]}.join end def decode(encoded, encoding) rev_enc = encoding.invert decoded = "" pos = 0 while pos < encoded.length key = "" while rev_enc[key].nil? key << encoded[pos] pos += 1 end decoded << rev_enc[key] end decoded end str = "this is an example for huffman encoding" encoding = huffman_encoding(str) encoding.to_a.sort.each {|x| p x} enc = encode(str, encoding) dec = decode(enc, encoding) puts "success!" if str == dec
<?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"; ?>
Generate an equivalent PHP version of this Scala code.
object Huffman { import scala.collection.mutable.{Map, PriorityQueue} sealed abstract class Tree case class Node(left: Tree, right: Tree) extends Tree case class Leaf(c: Char) extends Tree def treeOrdering(m: Map[Tree, Int]) = new Ordering[Tree] { def compare(x: Tree, y: Tree) = m(y).compare(m(x)) } def stringMap(text: String) = text groupBy (x => Leaf(x) : Tree) mapValues (_.length) def buildNode(queue: PriorityQueue[Tree], map: Map[Tree,Int]) { val right = queue.dequeue val left = queue.dequeue val node = Node(left, right) map(node) = map(left) + map(right) queue.enqueue(node) } def codify(tree: Tree, map: Map[Tree, Int]) = { def recurse(tree: Tree, prefix: String): List[(Char, (Int, String))] = tree match { case Node(left, right) => recurse(left, prefix+"0") ::: recurse(right, prefix+"1") case leaf @ Leaf(c) => c -> ((map(leaf), prefix)) :: Nil } recurse(tree, "") } def encode(text: String) = { val map = Map.empty[Tree,Int] ++= stringMap(text) val queue = new PriorityQueue[Tree]()(treeOrdering(map)) ++= map.keysIterator while(queue.size > 1) { buildNode(queue, map) } codify(queue.dequeue, map) } def main(args: Array[String]) { val text = "this is an example for huffman encoding" val code = encode(text) println("Char\tWeight\t\tEncoding") code sortBy (_._2._1) foreach { case (c, (weight, encoding)) => println("%c:\t%3d/%-3d\t\t%s" format (c, weight, text.length, encoding)) } } }
<?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"; ?>
Preserve the algorithm and functionality while converting the code from Swift to PHP.
enum HuffmanTree<T> { case Leaf(T) indirect case Node(HuffmanTree<T>, HuffmanTree<T>) func printCodes(prefix: String) { switch(self) { case let .Leaf(c): print("\(c)\t\(prefix)") case let .Node(l, r): l.printCodes(prefix + "0") r.printCodes(prefix + "1") } } } func buildTree<T>(freqs: [(T, Int)]) -> HuffmanTree<T> { assert(freqs.count > 0, "must contain at least one character") let leaves : [(Int, HuffmanTree<T>)] = freqs.sort { (p1, p2) in p1.1 < p2.1 }.map { (x, w) in (w, .Leaf(x)) } var nodes = [(Int, HuffmanTree<T>)]() for var i = 0, j = 0; ; { assert(i < leaves.count || j < nodes.count) var e1 : (Int, HuffmanTree<T>) if j == nodes.count || i < leaves.count && leaves[i].0 < nodes[j].0 { e1 = leaves[i] i++ } else { e1 = nodes[j] j++ } if i == leaves.count && j == nodes.count { return e1.1 } var e2 : (Int, HuffmanTree<T>) if j == nodes.count || i < leaves.count && leaves[i].0 < nodes[j].0 { e2 = leaves[i] i++ } else { e2 = nodes[j] j++ } nodes.append((e1.0 + e2.0, .Node(e1.1, e2.1))) } } func getFreqs<S : SequenceType where S.Generator.Element : Hashable>(seq: S) -> [(S.Generator.Element, Int)] { var freqs : [S.Generator.Element : Int] = [:] for c in seq { freqs[c] = (freqs[c] ?? 0) + 1 } return Array(freqs) } let str = "this is an example for huffman encoding" let charFreqs = getFreqs(str.characters) let tree = buildTree(charFreqs) print("Symbol\tHuffman code") tree.printCodes("")
<?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"; ?>
Change the following Tcl code into PHP without altering its purpose.
package require Tcl 8.5 package require struct::prioqueue proc huffmanEncode {str args} { array set opts [concat -dump false $args] set charcount [dict create] foreach char [split $str ""] { dict incr charcount $char } set pq [struct::prioqueue -dictionary] ; dict for {char count} $charcount { $pq put $char $count } while {[$pq size] > 1} { lassign [$pq peekpriority 2] p1 p2 $pq put [$pq get 2] [expr {$p1 + $p2}] } set encoding [walkTree [$pq get]] if {$opts(-dump)} { foreach {char huffCode} [lsort -index 1 -stride 2 -command compare $encoding] { puts "$char\t[dict get $charcount $char]\t$huffCode" } } $pq destroy return $encoding } proc walkTree {tree {prefix ""}} { if {[llength $tree] < 2} { return [list $tree $prefix] } lassign $tree left right return [concat [walkTree $left "${prefix}0"] [walkTree $right "${prefix}1"]] } proc compare {a b} { if {[string length $a] < [string length $b]} {return -1} if {[string length $a] > [string length $b]} {return 1} return [string compare $a $b] } set str "this is an example for huffman encoding" set encoding [huffmanEncode $str -dump true] puts $str puts [string map $encoding $str]
<?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"; ?>
Translate the given C code snippet into Rust without altering its behavior.
#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; }
use std::collections::BTreeMap; use std::collections::binary_heap::BinaryHeap; #[derive(Debug, Eq, PartialEq)] enum NodeKind { Internal(Box<Node>, Box<Node>), Leaf(char), } #[derive(Debug, Eq, PartialEq)] struct Node { frequency: usize, kind: NodeKind, } impl Ord for Node { fn cmp(&self, rhs: &Self) -> std::cmp::Ordering { rhs.frequency.cmp(&self.frequency) } } impl PartialOrd for Node { fn partial_cmp(&self, rhs: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(&rhs)) } } type HuffmanCodeMap = BTreeMap<char, Vec<u8>>; fn main() { let text = "this is an example for huffman encoding"; let mut frequencies = BTreeMap::new(); for ch in text.chars() { *frequencies.entry(ch).or_insert(0) += 1; } let mut prioritized_frequencies = BinaryHeap::new(); for counted_char in frequencies { prioritized_frequencies.push(Node { frequency: counted_char.1, kind: NodeKind::Leaf(counted_char.0), }); } while prioritized_frequencies.len() > 1 { let left_child = prioritized_frequencies.pop().unwrap(); let right_child = prioritized_frequencies.pop().unwrap(); prioritized_frequencies.push(Node { frequency: right_child.frequency + left_child.frequency, kind: NodeKind::Internal(Box::new(left_child), Box::new(right_child)), }); } let mut codes = HuffmanCodeMap::new(); generate_codes( prioritized_frequencies.peek().unwrap(), vec![0u8; 0], &mut codes, ); for item in codes { print!("{}: ", item.0); for bit in item.1 { print!("{}", bit); } println!(); } } fn generate_codes(node: &Node, prefix: Vec<u8>, out_codes: &mut HuffmanCodeMap) { match node.kind { NodeKind::Internal(ref left_child, ref right_child) => { let mut left_prefix = prefix.clone(); left_prefix.push(0); generate_codes(&left_child, left_prefix, out_codes); let mut right_prefix = prefix; right_prefix.push(1); generate_codes(&right_child, right_prefix, out_codes); } NodeKind::Leaf(ch) => { out_codes.insert(ch, prefix); } } }
Rewrite the snippet below in Rust so it works the same as the original C++ code.
#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; }
use std::collections::BTreeMap; use std::collections::binary_heap::BinaryHeap; #[derive(Debug, Eq, PartialEq)] enum NodeKind { Internal(Box<Node>, Box<Node>), Leaf(char), } #[derive(Debug, Eq, PartialEq)] struct Node { frequency: usize, kind: NodeKind, } impl Ord for Node { fn cmp(&self, rhs: &Self) -> std::cmp::Ordering { rhs.frequency.cmp(&self.frequency) } } impl PartialOrd for Node { fn partial_cmp(&self, rhs: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(&rhs)) } } type HuffmanCodeMap = BTreeMap<char, Vec<u8>>; fn main() { let text = "this is an example for huffman encoding"; let mut frequencies = BTreeMap::new(); for ch in text.chars() { *frequencies.entry(ch).or_insert(0) += 1; } let mut prioritized_frequencies = BinaryHeap::new(); for counted_char in frequencies { prioritized_frequencies.push(Node { frequency: counted_char.1, kind: NodeKind::Leaf(counted_char.0), }); } while prioritized_frequencies.len() > 1 { let left_child = prioritized_frequencies.pop().unwrap(); let right_child = prioritized_frequencies.pop().unwrap(); prioritized_frequencies.push(Node { frequency: right_child.frequency + left_child.frequency, kind: NodeKind::Internal(Box::new(left_child), Box::new(right_child)), }); } let mut codes = HuffmanCodeMap::new(); generate_codes( prioritized_frequencies.peek().unwrap(), vec![0u8; 0], &mut codes, ); for item in codes { print!("{}: ", item.0); for bit in item.1 { print!("{}", bit); } println!(); } } fn generate_codes(node: &Node, prefix: Vec<u8>, out_codes: &mut HuffmanCodeMap) { match node.kind { NodeKind::Internal(ref left_child, ref right_child) => { let mut left_prefix = prefix.clone(); left_prefix.push(0); generate_codes(&left_child, left_prefix, out_codes); let mut right_prefix = prefix; right_prefix.push(1); generate_codes(&right_child, right_prefix, out_codes); } NodeKind::Leaf(ch) => { out_codes.insert(ch, prefix); } } }
Rewrite the snippet below in Rust so it works the same as the original C# code.
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(); } } }
use std::collections::BTreeMap; use std::collections::binary_heap::BinaryHeap; #[derive(Debug, Eq, PartialEq)] enum NodeKind { Internal(Box<Node>, Box<Node>), Leaf(char), } #[derive(Debug, Eq, PartialEq)] struct Node { frequency: usize, kind: NodeKind, } impl Ord for Node { fn cmp(&self, rhs: &Self) -> std::cmp::Ordering { rhs.frequency.cmp(&self.frequency) } } impl PartialOrd for Node { fn partial_cmp(&self, rhs: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(&rhs)) } } type HuffmanCodeMap = BTreeMap<char, Vec<u8>>; fn main() { let text = "this is an example for huffman encoding"; let mut frequencies = BTreeMap::new(); for ch in text.chars() { *frequencies.entry(ch).or_insert(0) += 1; } let mut prioritized_frequencies = BinaryHeap::new(); for counted_char in frequencies { prioritized_frequencies.push(Node { frequency: counted_char.1, kind: NodeKind::Leaf(counted_char.0), }); } while prioritized_frequencies.len() > 1 { let left_child = prioritized_frequencies.pop().unwrap(); let right_child = prioritized_frequencies.pop().unwrap(); prioritized_frequencies.push(Node { frequency: right_child.frequency + left_child.frequency, kind: NodeKind::Internal(Box::new(left_child), Box::new(right_child)), }); } let mut codes = HuffmanCodeMap::new(); generate_codes( prioritized_frequencies.peek().unwrap(), vec![0u8; 0], &mut codes, ); for item in codes { print!("{}: ", item.0); for bit in item.1 { print!("{}", bit); } println!(); } } fn generate_codes(node: &Node, prefix: Vec<u8>, out_codes: &mut HuffmanCodeMap) { match node.kind { NodeKind::Internal(ref left_child, ref right_child) => { let mut left_prefix = prefix.clone(); left_prefix.push(0); generate_codes(&left_child, left_prefix, out_codes); let mut right_prefix = prefix; right_prefix.push(1); generate_codes(&right_child, right_prefix, out_codes); } NodeKind::Leaf(ch) => { out_codes.insert(ch, prefix); } } }
Change the programming language of this snippet from Java to Rust without modifying what it does.
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()); } }
use std::collections::BTreeMap; use std::collections::binary_heap::BinaryHeap; #[derive(Debug, Eq, PartialEq)] enum NodeKind { Internal(Box<Node>, Box<Node>), Leaf(char), } #[derive(Debug, Eq, PartialEq)] struct Node { frequency: usize, kind: NodeKind, } impl Ord for Node { fn cmp(&self, rhs: &Self) -> std::cmp::Ordering { rhs.frequency.cmp(&self.frequency) } } impl PartialOrd for Node { fn partial_cmp(&self, rhs: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(&rhs)) } } type HuffmanCodeMap = BTreeMap<char, Vec<u8>>; fn main() { let text = "this is an example for huffman encoding"; let mut frequencies = BTreeMap::new(); for ch in text.chars() { *frequencies.entry(ch).or_insert(0) += 1; } let mut prioritized_frequencies = BinaryHeap::new(); for counted_char in frequencies { prioritized_frequencies.push(Node { frequency: counted_char.1, kind: NodeKind::Leaf(counted_char.0), }); } while prioritized_frequencies.len() > 1 { let left_child = prioritized_frequencies.pop().unwrap(); let right_child = prioritized_frequencies.pop().unwrap(); prioritized_frequencies.push(Node { frequency: right_child.frequency + left_child.frequency, kind: NodeKind::Internal(Box::new(left_child), Box::new(right_child)), }); } let mut codes = HuffmanCodeMap::new(); generate_codes( prioritized_frequencies.peek().unwrap(), vec![0u8; 0], &mut codes, ); for item in codes { print!("{}: ", item.0); for bit in item.1 { print!("{}", bit); } println!(); } } fn generate_codes(node: &Node, prefix: Vec<u8>, out_codes: &mut HuffmanCodeMap) { match node.kind { NodeKind::Internal(ref left_child, ref right_child) => { let mut left_prefix = prefix.clone(); left_prefix.push(0); generate_codes(&left_child, left_prefix, out_codes); let mut right_prefix = prefix; right_prefix.push(1); generate_codes(&right_child, right_prefix, out_codes); } NodeKind::Leaf(ch) => { out_codes.insert(ch, prefix); } } }
Change the following Go code into Rust without altering its purpose.
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{}) }
use std::collections::BTreeMap; use std::collections::binary_heap::BinaryHeap; #[derive(Debug, Eq, PartialEq)] enum NodeKind { Internal(Box<Node>, Box<Node>), Leaf(char), } #[derive(Debug, Eq, PartialEq)] struct Node { frequency: usize, kind: NodeKind, } impl Ord for Node { fn cmp(&self, rhs: &Self) -> std::cmp::Ordering { rhs.frequency.cmp(&self.frequency) } } impl PartialOrd for Node { fn partial_cmp(&self, rhs: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(&rhs)) } } type HuffmanCodeMap = BTreeMap<char, Vec<u8>>; fn main() { let text = "this is an example for huffman encoding"; let mut frequencies = BTreeMap::new(); for ch in text.chars() { *frequencies.entry(ch).or_insert(0) += 1; } let mut prioritized_frequencies = BinaryHeap::new(); for counted_char in frequencies { prioritized_frequencies.push(Node { frequency: counted_char.1, kind: NodeKind::Leaf(counted_char.0), }); } while prioritized_frequencies.len() > 1 { let left_child = prioritized_frequencies.pop().unwrap(); let right_child = prioritized_frequencies.pop().unwrap(); prioritized_frequencies.push(Node { frequency: right_child.frequency + left_child.frequency, kind: NodeKind::Internal(Box::new(left_child), Box::new(right_child)), }); } let mut codes = HuffmanCodeMap::new(); generate_codes( prioritized_frequencies.peek().unwrap(), vec![0u8; 0], &mut codes, ); for item in codes { print!("{}: ", item.0); for bit in item.1 { print!("{}", bit); } println!(); } } fn generate_codes(node: &Node, prefix: Vec<u8>, out_codes: &mut HuffmanCodeMap) { match node.kind { NodeKind::Internal(ref left_child, ref right_child) => { let mut left_prefix = prefix.clone(); left_prefix.push(0); generate_codes(&left_child, left_prefix, out_codes); let mut right_prefix = prefix; right_prefix.push(1); generate_codes(&right_child, right_prefix, out_codes); } NodeKind::Leaf(ch) => { out_codes.insert(ch, prefix); } } }
Rewrite the snippet below in Python so it works the same as the original Rust code.
use std::collections::BTreeMap; use std::collections::binary_heap::BinaryHeap; #[derive(Debug, Eq, PartialEq)] enum NodeKind { Internal(Box<Node>, Box<Node>), Leaf(char), } #[derive(Debug, Eq, PartialEq)] struct Node { frequency: usize, kind: NodeKind, } impl Ord for Node { fn cmp(&self, rhs: &Self) -> std::cmp::Ordering { rhs.frequency.cmp(&self.frequency) } } impl PartialOrd for Node { fn partial_cmp(&self, rhs: &Self) -> Option<std::cmp::Ordering> { Some(self.cmp(&rhs)) } } type HuffmanCodeMap = BTreeMap<char, Vec<u8>>; fn main() { let text = "this is an example for huffman encoding"; let mut frequencies = BTreeMap::new(); for ch in text.chars() { *frequencies.entry(ch).or_insert(0) += 1; } let mut prioritized_frequencies = BinaryHeap::new(); for counted_char in frequencies { prioritized_frequencies.push(Node { frequency: counted_char.1, kind: NodeKind::Leaf(counted_char.0), }); } while prioritized_frequencies.len() > 1 { let left_child = prioritized_frequencies.pop().unwrap(); let right_child = prioritized_frequencies.pop().unwrap(); prioritized_frequencies.push(Node { frequency: right_child.frequency + left_child.frequency, kind: NodeKind::Internal(Box::new(left_child), Box::new(right_child)), }); } let mut codes = HuffmanCodeMap::new(); generate_codes( prioritized_frequencies.peek().unwrap(), vec![0u8; 0], &mut codes, ); for item in codes { print!("{}: ", item.0); for bit in item.1 { print!("{}", bit); } println!(); } } fn generate_codes(node: &Node, prefix: Vec<u8>, out_codes: &mut HuffmanCodeMap) { match node.kind { NodeKind::Internal(ref left_child, ref right_child) => { let mut left_prefix = prefix.clone(); left_prefix.push(0); generate_codes(&left_child, left_prefix, out_codes); let mut right_prefix = prefix; right_prefix.push(1); generate_codes(&right_child, right_prefix, out_codes); } NodeKind::Leaf(ch) => { out_codes.insert(ch, prefix); } } }
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 language-to-language conversion: from Ada to C#, same semantics.
with Ada.Text_IO; use Ada.Text_IO; procedure Main is type u_64 is mod 2**64; package u_64_io is new modular_io (u_64); use u_64_io; function Is_Prime (n : u_64) return Boolean is fact_Mod_n : u_64 := 1; begin if n < 2 then return False; end if; for i in 2 .. n - 1 loop fact_Mod_n := (fact_Mod_n * i) rem n; end loop; return fact_Mod_n = n - 1; end Is_Prime; num : u_64 := 1; type cols is mod 12; count : cols := 0; begin while num < 500 loop if Is_Prime (num) then if count = 0 then New_Line; end if; Put (Item => num, Width => 6); count := count + 1; end if; num := num + 1; end loop; end Main;
using System; using System.Linq; using System.Collections; using static System.Console; using System.Collections.Generic; using BI = System.Numerics.BigInteger; class Program { const int fst = 120, skp = 1000, max = 1015; static double et1, et2; static DateTime st; static string ms1 = "Wilson's theorem method", ms2 = "Sieve of Eratosthenes method", fmt = "--- {0} ---\n\nThe first {1} primes are:", fm2 = "{0} prime thru the {1} prime:"; static List<int> lst = new List<int>(); static void Dump(int s, int t, string f) { foreach (var item in lst.Skip(s).Take(t)) Write(f, item); WriteLine("\n"); } static string Ord(int x, string fmt = "{0:n0}") { var y = x % 10; if ((x % 100) / 10 == 10 || y > 3) y = 0; return string.Format(fmt, x) + "thstndrd".Substring(y << 1, 2); } static void ShowOne(string title, ref double et) { WriteLine(fmt, title, fst); Dump(0, fst, "{0,-3} "); WriteLine(fm2, Ord(skp), Ord(max)); Dump(skp - 1, max - skp + 1, "{0,4} "); WriteLine("Time taken: {0}ms\n", et = (DateTime.Now - st).TotalMilliseconds); } static BI factorial(int n) { BI res = 1; if (n < 2) return res; while (n > 0) res *= n--; return res; } static bool WTisPrimeSA(int n) { return ((factorial(n - 1) + 1) % n) == 0; } static BI[] facts; static void initFacts(int n) { facts = new BI[n]; facts[0] = facts[1] = 1; for (int i = 1, j = 2; j < n; i = j++) facts[j] = facts[i] * j; } static bool WTisPrime(int n) { return ((facts[n - 1] + 1) % n) == 0; } static void Main(string[] args) { st = DateTime.Now; BI f = 1; for (int n = 2; lst.Count < max; f *= n++) if ((f + 1) % n == 0) lst.Add(n); ShowOne(ms1, ref et1); st = DateTime.Now; int lmt = lst.Last(); lst.Clear(); BitArray flags = new BitArray(lmt + 1); for (int n = 2; n <= lmt; n+=n==2?1:2) if (!flags[n]) { lst.Add(n); for (int k = n * n, n2=n<<1; k <= lmt; k += n2) flags[k] = true; } ShowOne(ms2, ref et2); WriteLine("{0} was {1:0.0} times slower than the {2}.", ms1, et1 / et2, ms2); WriteLine("\n" + ms1 + " stand-alone computation:"); WriteLine("factorial computed for each item"); st = DateTime.Now; for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrimeSA(x)) Write("{0,4} ", x); WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds); WriteLine("factorials precomputed up to highest item"); st = DateTime.Now; initFacts(lst[max - 1]); for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrime(x)) Write("{0,4} ", x); WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds); } }
Can you help me rewrite this code in C instead of Ada, keeping it the same logically?
with Ada.Text_IO; use Ada.Text_IO; procedure Main is type u_64 is mod 2**64; package u_64_io is new modular_io (u_64); use u_64_io; function Is_Prime (n : u_64) return Boolean is fact_Mod_n : u_64 := 1; begin if n < 2 then return False; end if; for i in 2 .. n - 1 loop fact_Mod_n := (fact_Mod_n * i) rem n; end loop; return fact_Mod_n = n - 1; end Is_Prime; num : u_64 := 1; type cols is mod 12; count : cols := 0; begin while num < 500 loop if Is_Prime (num) then if count = 0 then New_Line; end if; Put (Item => num, Width => 6); count := count + 1; end if; num := num + 1; end loop; end Main;
#include <stdbool.h> #include <stdint.h> #include <stdio.h> uint64_t factorial(uint64_t n) { uint64_t product = 1; if (n < 2) { return 1; } for (; n > 0; n--) { uint64_t prev = product; product *= n; if (product < prev) { fprintf(stderr, "Overflowed\n"); return product; } } return product; } bool isPrime(uint64_t n) { uint64_t large = factorial(n - 1) + 1; return (large % n) == 0; } int main() { uint64_t n; for (n = 2; n < 22; n++) { printf("Is %llu prime: %d\n", n, isPrime(n)); } return 0; }
Write the same algorithm in C++ as shown in this Ada implementation.
with Ada.Text_IO; use Ada.Text_IO; procedure Main is type u_64 is mod 2**64; package u_64_io is new modular_io (u_64); use u_64_io; function Is_Prime (n : u_64) return Boolean is fact_Mod_n : u_64 := 1; begin if n < 2 then return False; end if; for i in 2 .. n - 1 loop fact_Mod_n := (fact_Mod_n * i) rem n; end loop; return fact_Mod_n = n - 1; end Is_Prime; num : u_64 := 1; type cols is mod 12; count : cols := 0; begin while num < 500 loop if Is_Prime (num) then if count = 0 then New_Line; end if; Put (Item => num, Width => 6); count := count + 1; end if; num := num + 1; end loop; end Main;
#include <iomanip> #include <iostream> int factorial_mod(int n, int p) { int f = 1; for (; n > 0 && f != 0; --n) f = (f * n) % p; return f; } bool is_prime(int p) { return p > 1 && factorial_mod(p - 1, p) == p - 1; } int main() { std::cout << " n | prime?\n------------\n"; std::cout << std::boolalpha; for (int p : {2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659}) std::cout << std::setw(3) << p << " | " << is_prime(p) << '\n'; std::cout << "\nFirst 120 primes by Wilson's theorem:\n"; int n = 0, p = 1; for (; n < 120; ++p) { if (is_prime(p)) std::cout << std::setw(3) << p << (++n % 20 == 0 ? '\n' : ' '); } std::cout << "\n1000th through 1015th primes:\n"; for (int i = 0; n < 1015; ++p) { if (is_prime(p)) { if (++n >= 1000) std::cout << std::setw(4) << p << (++i % 16 == 0 ? '\n' : ' '); } } }
Port the provided Ada code into Go while preserving the original functionality.
with Ada.Text_IO; use Ada.Text_IO; procedure Main is type u_64 is mod 2**64; package u_64_io is new modular_io (u_64); use u_64_io; function Is_Prime (n : u_64) return Boolean is fact_Mod_n : u_64 := 1; begin if n < 2 then return False; end if; for i in 2 .. n - 1 loop fact_Mod_n := (fact_Mod_n * i) rem n; end loop; return fact_Mod_n = n - 1; end Is_Prime; num : u_64 := 1; type cols is mod 12; count : cols := 0; begin while num < 500 loop if Is_Prime (num) then if count = 0 then New_Line; end if; Put (Item => num, Width => 6); count := count + 1; end if; num := num + 1; end loop; end Main;
package main import ( "fmt" "math/big" ) var ( zero = big.NewInt(0) one = big.NewInt(1) prev = big.NewInt(factorial(20)) ) func factorial(n int64) int64 { res := int64(1) for k := n; k > 1; k-- { res *= k } return res } func wilson(n int64, memo bool) bool { if n <= 1 || (n%2 == 0 && n != 2) { return false } if n <= 21 { return (factorial(n-1)+1)%n == 0 } b := big.NewInt(n) r := big.NewInt(0) z := big.NewInt(0) if !memo { z.MulRange(2, n-1) } else { prev.Mul(prev, r.MulRange(n-2, n-1)) z.Set(prev) } z.Add(z, one) return r.Rem(z, b).Cmp(zero) == 0 } func main() { numbers := []int64{2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659} fmt.Println(" n prime") fmt.Println("--- -----") for _, n := range numbers { fmt.Printf("%3d %t\n", n, wilson(n, false)) } fmt.Println("\nThe first 120 prime numbers are:") for i, count := int64(2), 0; count < 1015; i += 2 { if wilson(i, true) { count++ if count <= 120 { fmt.Printf("%3d ", i) if count%20 == 0 { fmt.Println() } } else if count >= 1000 { if count == 1000 { fmt.Println("\nThe 1,000th to 1,015th prime numbers are:") } fmt.Printf("%4d ", i) } } if i == 2 { i-- } } fmt.Println() }
Transform the following Ada implementation into Java, maintaining the same output and logic.
with Ada.Text_IO; use Ada.Text_IO; procedure Main is type u_64 is mod 2**64; package u_64_io is new modular_io (u_64); use u_64_io; function Is_Prime (n : u_64) return Boolean is fact_Mod_n : u_64 := 1; begin if n < 2 then return False; end if; for i in 2 .. n - 1 loop fact_Mod_n := (fact_Mod_n * i) rem n; end loop; return fact_Mod_n = n - 1; end Is_Prime; num : u_64 := 1; type cols is mod 12; count : cols := 0; begin while num < 500 loop if Is_Prime (num) then if count = 0 then New_Line; end if; Put (Item => num, Width => 6); count := count + 1; end if; num := num + 1; end loop; end Main;
import java.math.BigInteger; public class PrimaltyByWilsonsTheorem { public static void main(String[] args) { System.out.printf("Primes less than 100 testing by Wilson's Theorem%n"); for ( int i = 0 ; i <= 100 ; i++ ) { if ( isPrime(i) ) { System.out.printf("%d ", i); } } } private static boolean isPrime(long p) { if ( p <= 1) { return false; } return fact(p-1).add(BigInteger.ONE).mod(BigInteger.valueOf(p)).compareTo(BigInteger.ZERO) == 0; } private static BigInteger fact(long n) { BigInteger fact = BigInteger.ONE; for ( int i = 2 ; i <= n ; i++ ) { fact = fact.multiply(BigInteger.valueOf(i)); } return fact; } }
Produce a language-to-language conversion: from Ada to Python, same semantics.
with Ada.Text_IO; use Ada.Text_IO; procedure Main is type u_64 is mod 2**64; package u_64_io is new modular_io (u_64); use u_64_io; function Is_Prime (n : u_64) return Boolean is fact_Mod_n : u_64 := 1; begin if n < 2 then return False; end if; for i in 2 .. n - 1 loop fact_Mod_n := (fact_Mod_n * i) rem n; end loop; return fact_Mod_n = n - 1; end Is_Prime; num : u_64 := 1; type cols is mod 12; count : cols := 0; begin while num < 500 loop if Is_Prime (num) then if count = 0 then New_Line; end if; Put (Item => num, Width => 6); count := count + 1; end if; num := num + 1; end loop; end Main;
from math import factorial def is_wprime(n): return n == 2 or ( n > 1 and n % 2 != 0 and (factorial(n - 1) + 1) % n == 0 ) if __name__ == '__main__': c = int(input('Enter upper limit: ')) print(f'Primes under {c}:') print([n for n in range(c) if is_wprime(n)])
Convert the following code from Arturo to C, ensuring the logic remains intact.
factorial: function [x]-> product 1..x wprime?: function [n][ if n < 2 -> return false zero? mod add factorial sub n 1 1 n ] print "Primes below 20 via Wilson's theorem:" print select 1..20 => wprime?
#include <stdbool.h> #include <stdint.h> #include <stdio.h> uint64_t factorial(uint64_t n) { uint64_t product = 1; if (n < 2) { return 1; } for (; n > 0; n--) { uint64_t prev = product; product *= n; if (product < prev) { fprintf(stderr, "Overflowed\n"); return product; } } return product; } bool isPrime(uint64_t n) { uint64_t large = factorial(n - 1) + 1; return (large % n) == 0; } int main() { uint64_t n; for (n = 2; n < 22; n++) { printf("Is %llu prime: %d\n", n, isPrime(n)); } return 0; }
Transform the following Arturo implementation into C#, maintaining the same output and logic.
factorial: function [x]-> product 1..x wprime?: function [n][ if n < 2 -> return false zero? mod add factorial sub n 1 1 n ] print "Primes below 20 via Wilson's theorem:" print select 1..20 => wprime?
using System; using System.Linq; using System.Collections; using static System.Console; using System.Collections.Generic; using BI = System.Numerics.BigInteger; class Program { const int fst = 120, skp = 1000, max = 1015; static double et1, et2; static DateTime st; static string ms1 = "Wilson's theorem method", ms2 = "Sieve of Eratosthenes method", fmt = "--- {0} ---\n\nThe first {1} primes are:", fm2 = "{0} prime thru the {1} prime:"; static List<int> lst = new List<int>(); static void Dump(int s, int t, string f) { foreach (var item in lst.Skip(s).Take(t)) Write(f, item); WriteLine("\n"); } static string Ord(int x, string fmt = "{0:n0}") { var y = x % 10; if ((x % 100) / 10 == 10 || y > 3) y = 0; return string.Format(fmt, x) + "thstndrd".Substring(y << 1, 2); } static void ShowOne(string title, ref double et) { WriteLine(fmt, title, fst); Dump(0, fst, "{0,-3} "); WriteLine(fm2, Ord(skp), Ord(max)); Dump(skp - 1, max - skp + 1, "{0,4} "); WriteLine("Time taken: {0}ms\n", et = (DateTime.Now - st).TotalMilliseconds); } static BI factorial(int n) { BI res = 1; if (n < 2) return res; while (n > 0) res *= n--; return res; } static bool WTisPrimeSA(int n) { return ((factorial(n - 1) + 1) % n) == 0; } static BI[] facts; static void initFacts(int n) { facts = new BI[n]; facts[0] = facts[1] = 1; for (int i = 1, j = 2; j < n; i = j++) facts[j] = facts[i] * j; } static bool WTisPrime(int n) { return ((facts[n - 1] + 1) % n) == 0; } static void Main(string[] args) { st = DateTime.Now; BI f = 1; for (int n = 2; lst.Count < max; f *= n++) if ((f + 1) % n == 0) lst.Add(n); ShowOne(ms1, ref et1); st = DateTime.Now; int lmt = lst.Last(); lst.Clear(); BitArray flags = new BitArray(lmt + 1); for (int n = 2; n <= lmt; n+=n==2?1:2) if (!flags[n]) { lst.Add(n); for (int k = n * n, n2=n<<1; k <= lmt; k += n2) flags[k] = true; } ShowOne(ms2, ref et2); WriteLine("{0} was {1:0.0} times slower than the {2}.", ms1, et1 / et2, ms2); WriteLine("\n" + ms1 + " stand-alone computation:"); WriteLine("factorial computed for each item"); st = DateTime.Now; for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrimeSA(x)) Write("{0,4} ", x); WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds); WriteLine("factorials precomputed up to highest item"); st = DateTime.Now; initFacts(lst[max - 1]); for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrime(x)) Write("{0,4} ", x); WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds); } }
Preserve the algorithm and functionality while converting the code from Arturo to C++.
factorial: function [x]-> product 1..x wprime?: function [n][ if n < 2 -> return false zero? mod add factorial sub n 1 1 n ] print "Primes below 20 via Wilson's theorem:" print select 1..20 => wprime?
#include <iomanip> #include <iostream> int factorial_mod(int n, int p) { int f = 1; for (; n > 0 && f != 0; --n) f = (f * n) % p; return f; } bool is_prime(int p) { return p > 1 && factorial_mod(p - 1, p) == p - 1; } int main() { std::cout << " n | prime?\n------------\n"; std::cout << std::boolalpha; for (int p : {2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659}) std::cout << std::setw(3) << p << " | " << is_prime(p) << '\n'; std::cout << "\nFirst 120 primes by Wilson's theorem:\n"; int n = 0, p = 1; for (; n < 120; ++p) { if (is_prime(p)) std::cout << std::setw(3) << p << (++n % 20 == 0 ? '\n' : ' '); } std::cout << "\n1000th through 1015th primes:\n"; for (int i = 0; n < 1015; ++p) { if (is_prime(p)) { if (++n >= 1000) std::cout << std::setw(4) << p << (++i % 16 == 0 ? '\n' : ' '); } } }
Ensure the translated Java code behaves exactly like the original Arturo snippet.
factorial: function [x]-> product 1..x wprime?: function [n][ if n < 2 -> return false zero? mod add factorial sub n 1 1 n ] print "Primes below 20 via Wilson's theorem:" print select 1..20 => wprime?
import java.math.BigInteger; public class PrimaltyByWilsonsTheorem { public static void main(String[] args) { System.out.printf("Primes less than 100 testing by Wilson's Theorem%n"); for ( int i = 0 ; i <= 100 ; i++ ) { if ( isPrime(i) ) { System.out.printf("%d ", i); } } } private static boolean isPrime(long p) { if ( p <= 1) { return false; } return fact(p-1).add(BigInteger.ONE).mod(BigInteger.valueOf(p)).compareTo(BigInteger.ZERO) == 0; } private static BigInteger fact(long n) { BigInteger fact = BigInteger.ONE; for ( int i = 2 ; i <= n ; i++ ) { fact = fact.multiply(BigInteger.valueOf(i)); } return fact; } }
Rewrite the snippet below in Python so it works the same as the original Arturo code.
factorial: function [x]-> product 1..x wprime?: function [n][ if n < 2 -> return false zero? mod add factorial sub n 1 1 n ] print "Primes below 20 via Wilson's theorem:" print select 1..20 => wprime?
from math import factorial def is_wprime(n): return n == 2 or ( n > 1 and n % 2 != 0 and (factorial(n - 1) + 1) % n == 0 ) if __name__ == '__main__': c = int(input('Enter upper limit: ')) print(f'Primes under {c}:') print([n for n in range(c) if is_wprime(n)])
Rewrite the snippet below in Go so it works the same as the original Arturo code.
factorial: function [x]-> product 1..x wprime?: function [n][ if n < 2 -> return false zero? mod add factorial sub n 1 1 n ] print "Primes below 20 via Wilson's theorem:" print select 1..20 => wprime?
package main import ( "fmt" "math/big" ) var ( zero = big.NewInt(0) one = big.NewInt(1) prev = big.NewInt(factorial(20)) ) func factorial(n int64) int64 { res := int64(1) for k := n; k > 1; k-- { res *= k } return res } func wilson(n int64, memo bool) bool { if n <= 1 || (n%2 == 0 && n != 2) { return false } if n <= 21 { return (factorial(n-1)+1)%n == 0 } b := big.NewInt(n) r := big.NewInt(0) z := big.NewInt(0) if !memo { z.MulRange(2, n-1) } else { prev.Mul(prev, r.MulRange(n-2, n-1)) z.Set(prev) } z.Add(z, one) return r.Rem(z, b).Cmp(zero) == 0 } func main() { numbers := []int64{2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659} fmt.Println(" n prime") fmt.Println("--- -----") for _, n := range numbers { fmt.Printf("%3d %t\n", n, wilson(n, false)) } fmt.Println("\nThe first 120 prime numbers are:") for i, count := int64(2), 0; count < 1015; i += 2 { if wilson(i, true) { count++ if count <= 120 { fmt.Printf("%3d ", i) if count%20 == 0 { fmt.Println() } } else if count >= 1000 { if count == 1000 { fmt.Println("\nThe 1,000th to 1,015th prime numbers are:") } fmt.Printf("%4d ", i) } } if i == 2 { i-- } } fmt.Println() }
Write the same code in C as shown below in AWK.
BEGIN { start = 2 stop = 200 for (i=start; i<=stop; i++) { if (is_wilson_prime(i)) { printf("%5d%1s",i,++count%10?"":"\n") } } printf("\nWilson primality test range %d-%d: %d\n",start,stop,count) exit(0) } function is_wilson_prime(n, fct,i) { fct = 1 for (i=2; i<=n-1; i++) { fct = (fct * i) % n } return(fct == n-1) }
#include <stdbool.h> #include <stdint.h> #include <stdio.h> uint64_t factorial(uint64_t n) { uint64_t product = 1; if (n < 2) { return 1; } for (; n > 0; n--) { uint64_t prev = product; product *= n; if (product < prev) { fprintf(stderr, "Overflowed\n"); return product; } } return product; } bool isPrime(uint64_t n) { uint64_t large = factorial(n - 1) + 1; return (large % n) == 0; } int main() { uint64_t n; for (n = 2; n < 22; n++) { printf("Is %llu prime: %d\n", n, isPrime(n)); } return 0; }
Ensure the translated C# code behaves exactly like the original AWK snippet.
BEGIN { start = 2 stop = 200 for (i=start; i<=stop; i++) { if (is_wilson_prime(i)) { printf("%5d%1s",i,++count%10?"":"\n") } } printf("\nWilson primality test range %d-%d: %d\n",start,stop,count) exit(0) } function is_wilson_prime(n, fct,i) { fct = 1 for (i=2; i<=n-1; i++) { fct = (fct * i) % n } return(fct == n-1) }
using System; using System.Linq; using System.Collections; using static System.Console; using System.Collections.Generic; using BI = System.Numerics.BigInteger; class Program { const int fst = 120, skp = 1000, max = 1015; static double et1, et2; static DateTime st; static string ms1 = "Wilson's theorem method", ms2 = "Sieve of Eratosthenes method", fmt = "--- {0} ---\n\nThe first {1} primes are:", fm2 = "{0} prime thru the {1} prime:"; static List<int> lst = new List<int>(); static void Dump(int s, int t, string f) { foreach (var item in lst.Skip(s).Take(t)) Write(f, item); WriteLine("\n"); } static string Ord(int x, string fmt = "{0:n0}") { var y = x % 10; if ((x % 100) / 10 == 10 || y > 3) y = 0; return string.Format(fmt, x) + "thstndrd".Substring(y << 1, 2); } static void ShowOne(string title, ref double et) { WriteLine(fmt, title, fst); Dump(0, fst, "{0,-3} "); WriteLine(fm2, Ord(skp), Ord(max)); Dump(skp - 1, max - skp + 1, "{0,4} "); WriteLine("Time taken: {0}ms\n", et = (DateTime.Now - st).TotalMilliseconds); } static BI factorial(int n) { BI res = 1; if (n < 2) return res; while (n > 0) res *= n--; return res; } static bool WTisPrimeSA(int n) { return ((factorial(n - 1) + 1) % n) == 0; } static BI[] facts; static void initFacts(int n) { facts = new BI[n]; facts[0] = facts[1] = 1; for (int i = 1, j = 2; j < n; i = j++) facts[j] = facts[i] * j; } static bool WTisPrime(int n) { return ((facts[n - 1] + 1) % n) == 0; } static void Main(string[] args) { st = DateTime.Now; BI f = 1; for (int n = 2; lst.Count < max; f *= n++) if ((f + 1) % n == 0) lst.Add(n); ShowOne(ms1, ref et1); st = DateTime.Now; int lmt = lst.Last(); lst.Clear(); BitArray flags = new BitArray(lmt + 1); for (int n = 2; n <= lmt; n+=n==2?1:2) if (!flags[n]) { lst.Add(n); for (int k = n * n, n2=n<<1; k <= lmt; k += n2) flags[k] = true; } ShowOne(ms2, ref et2); WriteLine("{0} was {1:0.0} times slower than the {2}.", ms1, et1 / et2, ms2); WriteLine("\n" + ms1 + " stand-alone computation:"); WriteLine("factorial computed for each item"); st = DateTime.Now; for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrimeSA(x)) Write("{0,4} ", x); WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds); WriteLine("factorials precomputed up to highest item"); st = DateTime.Now; initFacts(lst[max - 1]); for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrime(x)) Write("{0,4} ", x); WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds); } }
Please provide an equivalent version of this AWK code in C++.
BEGIN { start = 2 stop = 200 for (i=start; i<=stop; i++) { if (is_wilson_prime(i)) { printf("%5d%1s",i,++count%10?"":"\n") } } printf("\nWilson primality test range %d-%d: %d\n",start,stop,count) exit(0) } function is_wilson_prime(n, fct,i) { fct = 1 for (i=2; i<=n-1; i++) { fct = (fct * i) % n } return(fct == n-1) }
#include <iomanip> #include <iostream> int factorial_mod(int n, int p) { int f = 1; for (; n > 0 && f != 0; --n) f = (f * n) % p; return f; } bool is_prime(int p) { return p > 1 && factorial_mod(p - 1, p) == p - 1; } int main() { std::cout << " n | prime?\n------------\n"; std::cout << std::boolalpha; for (int p : {2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659}) std::cout << std::setw(3) << p << " | " << is_prime(p) << '\n'; std::cout << "\nFirst 120 primes by Wilson's theorem:\n"; int n = 0, p = 1; for (; n < 120; ++p) { if (is_prime(p)) std::cout << std::setw(3) << p << (++n % 20 == 0 ? '\n' : ' '); } std::cout << "\n1000th through 1015th primes:\n"; for (int i = 0; n < 1015; ++p) { if (is_prime(p)) { if (++n >= 1000) std::cout << std::setw(4) << p << (++i % 16 == 0 ? '\n' : ' '); } } }
Keep all operations the same but rewrite the snippet in Java.
BEGIN { start = 2 stop = 200 for (i=start; i<=stop; i++) { if (is_wilson_prime(i)) { printf("%5d%1s",i,++count%10?"":"\n") } } printf("\nWilson primality test range %d-%d: %d\n",start,stop,count) exit(0) } function is_wilson_prime(n, fct,i) { fct = 1 for (i=2; i<=n-1; i++) { fct = (fct * i) % n } return(fct == n-1) }
import java.math.BigInteger; public class PrimaltyByWilsonsTheorem { public static void main(String[] args) { System.out.printf("Primes less than 100 testing by Wilson's Theorem%n"); for ( int i = 0 ; i <= 100 ; i++ ) { if ( isPrime(i) ) { System.out.printf("%d ", i); } } } private static boolean isPrime(long p) { if ( p <= 1) { return false; } return fact(p-1).add(BigInteger.ONE).mod(BigInteger.valueOf(p)).compareTo(BigInteger.ZERO) == 0; } private static BigInteger fact(long n) { BigInteger fact = BigInteger.ONE; for ( int i = 2 ; i <= n ; i++ ) { fact = fact.multiply(BigInteger.valueOf(i)); } return fact; } }
Generate an equivalent Python version of this AWK code.
BEGIN { start = 2 stop = 200 for (i=start; i<=stop; i++) { if (is_wilson_prime(i)) { printf("%5d%1s",i,++count%10?"":"\n") } } printf("\nWilson primality test range %d-%d: %d\n",start,stop,count) exit(0) } function is_wilson_prime(n, fct,i) { fct = 1 for (i=2; i<=n-1; i++) { fct = (fct * i) % n } return(fct == n-1) }
from math import factorial def is_wprime(n): return n == 2 or ( n > 1 and n % 2 != 0 and (factorial(n - 1) + 1) % n == 0 ) if __name__ == '__main__': c = int(input('Enter upper limit: ')) print(f'Primes under {c}:') print([n for n in range(c) if is_wprime(n)])
Generate a Go translation of this AWK snippet without changing its computational steps.
BEGIN { start = 2 stop = 200 for (i=start; i<=stop; i++) { if (is_wilson_prime(i)) { printf("%5d%1s",i,++count%10?"":"\n") } } printf("\nWilson primality test range %d-%d: %d\n",start,stop,count) exit(0) } function is_wilson_prime(n, fct,i) { fct = 1 for (i=2; i<=n-1; i++) { fct = (fct * i) % n } return(fct == n-1) }
package main import ( "fmt" "math/big" ) var ( zero = big.NewInt(0) one = big.NewInt(1) prev = big.NewInt(factorial(20)) ) func factorial(n int64) int64 { res := int64(1) for k := n; k > 1; k-- { res *= k } return res } func wilson(n int64, memo bool) bool { if n <= 1 || (n%2 == 0 && n != 2) { return false } if n <= 21 { return (factorial(n-1)+1)%n == 0 } b := big.NewInt(n) r := big.NewInt(0) z := big.NewInt(0) if !memo { z.MulRange(2, n-1) } else { prev.Mul(prev, r.MulRange(n-2, n-1)) z.Set(prev) } z.Add(z, one) return r.Rem(z, b).Cmp(zero) == 0 } func main() { numbers := []int64{2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659} fmt.Println(" n prime") fmt.Println("--- -----") for _, n := range numbers { fmt.Printf("%3d %t\n", n, wilson(n, false)) } fmt.Println("\nThe first 120 prime numbers are:") for i, count := int64(2), 0; count < 1015; i += 2 { if wilson(i, true) { count++ if count <= 120 { fmt.Printf("%3d ", i) if count%20 == 0 { fmt.Println() } } else if count >= 1000 { if count == 1000 { fmt.Println("\nThe 1,000th to 1,015th prime numbers are:") } fmt.Printf("%4d ", i) } } if i == 2 { i-- } } fmt.Println() }
Can you help me rewrite this code in C instead of Common_Lisp, keeping it the same logically?
(defun factorial (n) (if (< n 2) 1 (* n (factorial (1- n)))) ) (defun primep (n) "Primality test using Wilson's Theorem" (unless (zerop n) (zerop (mod (1+ (factorial (1- n))) n)) ))
#include <stdbool.h> #include <stdint.h> #include <stdio.h> uint64_t factorial(uint64_t n) { uint64_t product = 1; if (n < 2) { return 1; } for (; n > 0; n--) { uint64_t prev = product; product *= n; if (product < prev) { fprintf(stderr, "Overflowed\n"); return product; } } return product; } bool isPrime(uint64_t n) { uint64_t large = factorial(n - 1) + 1; return (large % n) == 0; } int main() { uint64_t n; for (n = 2; n < 22; n++) { printf("Is %llu prime: %d\n", n, isPrime(n)); } return 0; }
Maintain the same structure and functionality when rewriting this code in C#.
(defun factorial (n) (if (< n 2) 1 (* n (factorial (1- n)))) ) (defun primep (n) "Primality test using Wilson's Theorem" (unless (zerop n) (zerop (mod (1+ (factorial (1- n))) n)) ))
using System; using System.Linq; using System.Collections; using static System.Console; using System.Collections.Generic; using BI = System.Numerics.BigInteger; class Program { const int fst = 120, skp = 1000, max = 1015; static double et1, et2; static DateTime st; static string ms1 = "Wilson's theorem method", ms2 = "Sieve of Eratosthenes method", fmt = "--- {0} ---\n\nThe first {1} primes are:", fm2 = "{0} prime thru the {1} prime:"; static List<int> lst = new List<int>(); static void Dump(int s, int t, string f) { foreach (var item in lst.Skip(s).Take(t)) Write(f, item); WriteLine("\n"); } static string Ord(int x, string fmt = "{0:n0}") { var y = x % 10; if ((x % 100) / 10 == 10 || y > 3) y = 0; return string.Format(fmt, x) + "thstndrd".Substring(y << 1, 2); } static void ShowOne(string title, ref double et) { WriteLine(fmt, title, fst); Dump(0, fst, "{0,-3} "); WriteLine(fm2, Ord(skp), Ord(max)); Dump(skp - 1, max - skp + 1, "{0,4} "); WriteLine("Time taken: {0}ms\n", et = (DateTime.Now - st).TotalMilliseconds); } static BI factorial(int n) { BI res = 1; if (n < 2) return res; while (n > 0) res *= n--; return res; } static bool WTisPrimeSA(int n) { return ((factorial(n - 1) + 1) % n) == 0; } static BI[] facts; static void initFacts(int n) { facts = new BI[n]; facts[0] = facts[1] = 1; for (int i = 1, j = 2; j < n; i = j++) facts[j] = facts[i] * j; } static bool WTisPrime(int n) { return ((facts[n - 1] + 1) % n) == 0; } static void Main(string[] args) { st = DateTime.Now; BI f = 1; for (int n = 2; lst.Count < max; f *= n++) if ((f + 1) % n == 0) lst.Add(n); ShowOne(ms1, ref et1); st = DateTime.Now; int lmt = lst.Last(); lst.Clear(); BitArray flags = new BitArray(lmt + 1); for (int n = 2; n <= lmt; n+=n==2?1:2) if (!flags[n]) { lst.Add(n); for (int k = n * n, n2=n<<1; k <= lmt; k += n2) flags[k] = true; } ShowOne(ms2, ref et2); WriteLine("{0} was {1:0.0} times slower than the {2}.", ms1, et1 / et2, ms2); WriteLine("\n" + ms1 + " stand-alone computation:"); WriteLine("factorial computed for each item"); st = DateTime.Now; for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrimeSA(x)) Write("{0,4} ", x); WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds); WriteLine("factorials precomputed up to highest item"); st = DateTime.Now; initFacts(lst[max - 1]); for (int x = lst[skp - 1]; x <= lst[max - 1]; x++) if (WTisPrime(x)) Write("{0,4} ", x); WriteLine(); WriteLine("\nTime taken: {0}ms\n", (DateTime.Now - st).TotalMilliseconds); } }
Translate this program into C++ but keep the logic exactly as in Common_Lisp.
(defun factorial (n) (if (< n 2) 1 (* n (factorial (1- n)))) ) (defun primep (n) "Primality test using Wilson's Theorem" (unless (zerop n) (zerop (mod (1+ (factorial (1- n))) n)) ))
#include <iomanip> #include <iostream> int factorial_mod(int n, int p) { int f = 1; for (; n > 0 && f != 0; --n) f = (f * n) % p; return f; } bool is_prime(int p) { return p > 1 && factorial_mod(p - 1, p) == p - 1; } int main() { std::cout << " n | prime?\n------------\n"; std::cout << std::boolalpha; for (int p : {2, 3, 9, 15, 29, 37, 47, 57, 67, 77, 87, 97, 237, 409, 659}) std::cout << std::setw(3) << p << " | " << is_prime(p) << '\n'; std::cout << "\nFirst 120 primes by Wilson's theorem:\n"; int n = 0, p = 1; for (; n < 120; ++p) { if (is_prime(p)) std::cout << std::setw(3) << p << (++n % 20 == 0 ? '\n' : ' '); } std::cout << "\n1000th through 1015th primes:\n"; for (int i = 0; n < 1015; ++p) { if (is_prime(p)) { if (++n >= 1000) std::cout << std::setw(4) << p << (++i % 16 == 0 ? '\n' : ' '); } } }
Preserve the algorithm and functionality while converting the code from Common_Lisp to Java.
(defun factorial (n) (if (< n 2) 1 (* n (factorial (1- n)))) ) (defun primep (n) "Primality test using Wilson's Theorem" (unless (zerop n) (zerop (mod (1+ (factorial (1- n))) n)) ))
import java.math.BigInteger; public class PrimaltyByWilsonsTheorem { public static void main(String[] args) { System.out.printf("Primes less than 100 testing by Wilson's Theorem%n"); for ( int i = 0 ; i <= 100 ; i++ ) { if ( isPrime(i) ) { System.out.printf("%d ", i); } } } private static boolean isPrime(long p) { if ( p <= 1) { return false; } return fact(p-1).add(BigInteger.ONE).mod(BigInteger.valueOf(p)).compareTo(BigInteger.ZERO) == 0; } private static BigInteger fact(long n) { BigInteger fact = BigInteger.ONE; for ( int i = 2 ; i <= n ; i++ ) { fact = fact.multiply(BigInteger.valueOf(i)); } return fact; } }
Rewrite the snippet below in Python so it works the same as the original Common_Lisp code.
(defun factorial (n) (if (< n 2) 1 (* n (factorial (1- n)))) ) (defun primep (n) "Primality test using Wilson's Theorem" (unless (zerop n) (zerop (mod (1+ (factorial (1- n))) n)) ))
from math import factorial def is_wprime(n): return n == 2 or ( n > 1 and n % 2 != 0 and (factorial(n - 1) + 1) % n == 0 ) if __name__ == '__main__': c = int(input('Enter upper limit: ')) print(f'Primes under {c}:') print([n for n in range(c) if is_wprime(n)])