something like a huffman trie
This commit is contained in:
parent
3dfc7e093f
commit
2d48a86f5e
1 changed files with 26 additions and 13 deletions
33
huffman.go
33
huffman.go
|
@ -16,16 +16,22 @@ func (n Node) Lookup(value interface{}) *Node {
|
||||||
}
|
}
|
||||||
|
|
||||||
func NewPathTree(paths []string) *Node {
|
func NewPathTree(paths []string) *Node {
|
||||||
nodes := []Node{}
|
nodes := []*Node{}
|
||||||
for i := range paths {
|
for i := range paths {
|
||||||
node := Node{Weight: int64(i + 1), Value: paths[i]}
|
nodes = append(nodes, &Node{Weight: int64(i + 1), Value: paths[i]})
|
||||||
nodes = append(nodes, node)
|
|
||||||
}
|
}
|
||||||
|
|
||||||
nodeHeap := nodeInterface(nodes)
|
h := nodeInterface(nodes)
|
||||||
heap.Init(nodeHeap)
|
h_ptr := &h
|
||||||
|
heap.Init(h_ptr)
|
||||||
return &Node{}
|
count := h_ptr.Len()
|
||||||
|
for count > 1 {
|
||||||
|
left := heap.Pop(h_ptr)
|
||||||
|
right := heap.Pop(h_ptr)
|
||||||
|
heap.Push(h_ptr, Combine(left.(*Node), right.(*Node)))
|
||||||
|
count = h_ptr.Len()
|
||||||
|
}
|
||||||
|
return heap.Pop(h_ptr).(*Node)
|
||||||
}
|
}
|
||||||
|
|
||||||
func Combine(left *Node, right *Node) *Node {
|
func Combine(left *Node, right *Node) *Node {
|
||||||
|
@ -43,10 +49,17 @@ func Combine(left *Node, right *Node) *Node {
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
type nodeInterface []Node
|
type nodeInterface []*Node
|
||||||
|
|
||||||
func (ni nodeInterface) Push(x interface{}) {}
|
|
||||||
func (ni nodeInterface) Pop() interface{} { return Node{} }
|
|
||||||
func (ni nodeInterface) Len() int { return len(ni) }
|
func (ni nodeInterface) Len() int { return len(ni) }
|
||||||
func (ni nodeInterface) Less(i, j int) bool { return ni[i].Weight < ni[j].Weight }
|
func (ni nodeInterface) Less(i, j int) bool { return ni[i].Weight < ni[j].Weight }
|
||||||
func (ni nodeInterface) Swap(i, j int) { ni[i], ni[j] = ni[j], ni[i] }
|
func (ni nodeInterface) Swap(i, j int) { ni[i], ni[j] = ni[j], ni[i] }
|
||||||
|
func (ni *nodeInterface) Push(x interface{}) { *ni = append(*ni, x.(*Node)) }
|
||||||
|
func (ni *nodeInterface) Pop() interface{} {
|
||||||
|
old := *ni
|
||||||
|
n := len(old)
|
||||||
|
x := old[n-1]
|
||||||
|
*ni = old[0 : n-1]
|
||||||
|
return x
|
||||||
|
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in a new issue