golang huffman
来源:互联网 发布:c语言 char 编辑:程序博客网 时间:2024/06/05 12:42
// Huffman Coding in Golangpackage mainimport ( "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 []HuffmanTreefunc (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] }// The main function that builds a Huffman Tree and print codes by traversing// the built Huffman Treefunc 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 { // two trees with least frequency a := heap.Pop(&trees).(HuffmanTree) b := heap.Pop(&trees).(HuffmanTree) // put into new node and re-insert into queue heap.Push(&trees, HuffmanNode{a.Freq() + b.Freq(), a, b}) } return heap.Pop(&trees).(HuffmanTree)}// Prints huffman codes from the root of Huffman Tree. It uses byte[] to// store codesfunc printCodes(tree HuffmanTree, prefix []byte) { switch i := tree.(type) { case HuffmanLeaf: // If this is a leaf node, then it contains one of the input // characters, print the character and its code from byte[] fmt.Printf("%c\t%d\t%s\n", i.value, i.freq, string(prefix)) case HuffmanNode: // Assign 0 to left edge and recur prefix = append(prefix, '0') printCodes(i.left, prefix) prefix = prefix[:len(prefix)-1] // Assign 1 to right edge and recur prefix = append(prefix, '1') printCodes(i.right, prefix) prefix = prefix[:len(prefix)-1] }}// Driver program to test above functionsfunc main() { test := "abcdefghijklmnopqrstuvwxyz" symFreqs := make(map[rune]int) // read each symbol and record the frequencies for _, c := range test { symFreqs[c]++ } // example tree exampleTree := buildTree(symFreqs) // print out results fmt.Println("SYMBOL\tWEIGHT\tHUFFMAN CODE") printCodes(exampleTree, []byte{})}
阅读全文
0 0
- golang huffman
- Huffman Coding: the golang version of SelectTwoMinimumValue
- Huffman
- Huffman
- huffman
- huffman
- Huffman
- Huffman
- huffman
- huffman
- Huffman
- huffman
- Huffman
- Huffman
- Huffman
- Golang
- golang
- golang
- 进程通信 详解
- 多线程小例子
- 找出mysql中的慢语句
- 【BZOJ 4347】[POI2016]Nim z utrudnieniem
- SAS中intck函数计算日期天数间隔等妙用
- golang huffman
- 阿里云设置远程连接reids
- 从零开始前端学习[13]:伪类选择器
- 7.排序、聚合函数、分组查询
- angularjs速成学习个人理解_2表达式
- 敌兵布阵(简单线段树)
- JavaScript深入学习[1]
- vue-cli 路由嵌套
- 第一篇:对jni和NDK的认识