├── LICENSE ├── Readme.md ├── collections.go ├── grid └── grid.go ├── point.go ├── queue ├── queue.go └── queue_test.go ├── set ├── set.go └── set_test.go ├── skip ├── skip.go └── skip_test.go ├── splay ├── splay.go └── splay_test.go ├── stack ├── stack.go └── stack_test.go ├── trie ├── trie.go └── trie_test.go └── tst ├── tst.go └── tst_test.go /LICENSE: -------------------------------------------------------------------------------- 1 | Copyright (c) 2012 Caleb Doxsey 2 | 3 | Permission is hereby granted, free of charge, to any person obtaining 4 | a copy of this software and associated documentation files (the 5 | "Software"), to deal in the Software without restriction, including 6 | without limitation the rights to use, copy, modify, merge, publish, 7 | distribute, sublicense, and/or sell copies of the Software, and to 8 | permit persons to whom the Software is furnished to do so, subject to 9 | the following conditions: 10 | 11 | The above copyright notice and this permission notice shall be included 12 | in all copies or substantial portions of the Software. 13 | 14 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, 15 | EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF 16 | MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. 17 | IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY 18 | CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, 19 | TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE 20 | SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. -------------------------------------------------------------------------------- /Readme.md: -------------------------------------------------------------------------------- 1 | # Badgerodon Collections 2 | 3 | Maps and slices go a long way in Go, but sometimes you need more. This is a collection of collections that may be useful. 4 | 5 | ## Queue 6 | A [queue](http://en.wikipedia.org/wiki/Queue_(data_structure%29) is a first-in first-out data structure. 7 | 8 | ## Set 9 | A [set](http://en.wikipedia.org/wiki/Set_(computer_science%29) is an unordered collection of unique values typically used for testing membership. 10 | 11 | ## Skip list 12 | A [skip list](http://en.wikipedia.org/wiki/Skip_list) is a data structure that stores nodes in a hierarchy of linked lists. It gives performance similar to binary search trees by using a random number of forward links to skip parts of the list. 13 | 14 | ## Splay Tree 15 | 16 | A [splay tree](http://en.wikipedia.org/wiki/Splay_tree) is a type of binary search tree where every access to the tree results in the tree being rearranged so that the current node gets put on top. 17 | 18 | ## Stack 19 | A [stack](http://en.wikipedia.org/wiki/Stack_(abstract_data_type%29) is a last-in last-out data structure. 20 | 21 | ## Trie 22 | A [trie](http://en.wikipedia.org/wiki/Trie) is a type of tree where each node represents one byte of a key. 23 | 24 | ## Ternary Search Tree 25 | 26 | A [ternary search tree](http://en.wikipedia.org/wiki/Ternary_search_tree) is similar to a trie in that nodes store the letters of the key, but instead of either using a list or hash at each node a binary tree is used. Ternary search trees have the performance benefits of a trie without the usual memory costs. -------------------------------------------------------------------------------- /collections.go: -------------------------------------------------------------------------------- 1 | package collections 2 | 3 | type ( 4 | Collection interface { 5 | Do(func(interface{})bool) 6 | } 7 | ) 8 | 9 | func GetRange(c Collection, start, length int) []interface{} { 10 | end := start + length 11 | items := make([]interface{}, length) 12 | i := 0 13 | j := 0 14 | c.Do(func(item interface{})bool{ 15 | if i >= start { 16 | if i < end { 17 | items[j] = item 18 | j++ 19 | } else { 20 | return false 21 | } 22 | } 23 | i++ 24 | return true 25 | }) 26 | return items[:j] 27 | } 28 | -------------------------------------------------------------------------------- /grid/grid.go: -------------------------------------------------------------------------------- 1 | package grid 2 | 3 | import ( 4 | . "github.com/badgerodon/collections" 5 | ) 6 | 7 | type ( 8 | Grid struct { 9 | values []interface{} 10 | cols, rows int 11 | } 12 | ) 13 | 14 | func New(cols, rows int) *Grid { 15 | return &Grid{ 16 | values: make([]interface{}, cols*rows), 17 | cols: cols, 18 | rows: rows, 19 | } 20 | } 21 | 22 | func (this *Grid) Do(f func(p Point, value interface{})) { 23 | for x := 0; x < this.cols; x++ { 24 | for y := 0; y < this.rows; y++ { 25 | f(Point{x, y}, this.values[x*this.cols+y]) 26 | } 27 | } 28 | } 29 | 30 | func (this *Grid) Get(p Point) interface{} { 31 | if p.X < 0 || p.Y < 0 || p.X >= this.cols || p.Y >= this.rows { 32 | return nil 33 | } 34 | v, _ := this.values[p.X*this.cols+p.Y] 35 | return v 36 | } 37 | 38 | func (this *Grid) Rows() int { 39 | return this.rows 40 | } 41 | 42 | func (this *Grid) Cols() int { 43 | return this.cols 44 | } 45 | 46 | func (this *Grid) Len() int { 47 | return this.rows * this.cols 48 | } 49 | 50 | func (this *Grid) Set(p Point, v interface{}) { 51 | 52 | } 53 | -------------------------------------------------------------------------------- /point.go: -------------------------------------------------------------------------------- 1 | package collections 2 | 3 | type ( 4 | Point struct { 5 | X, Y int 6 | } 7 | ) 8 | -------------------------------------------------------------------------------- /queue/queue.go: -------------------------------------------------------------------------------- 1 | package queue 2 | 3 | type ( 4 | Queue struct { 5 | start, end *node 6 | length int 7 | } 8 | node struct { 9 | value interface{} 10 | next *node 11 | } 12 | ) 13 | 14 | // Create a new queue 15 | func New() *Queue { 16 | return &Queue{nil,nil,0} 17 | } 18 | // Take the next item off the front of the queue 19 | func (this *Queue) Dequeue() interface{} { 20 | if this.length == 0 { 21 | return nil 22 | } 23 | n := this.start 24 | if this.length == 1 { 25 | this.start = nil 26 | this.end = nil 27 | } else { 28 | this.start = this.start.next 29 | } 30 | this.length-- 31 | return n.value 32 | } 33 | // Put an item on the end of a queue 34 | func (this *Queue) Enqueue(value interface{}) { 35 | n := &node{value,nil} 36 | if this.length == 0 { 37 | this.start = n 38 | this.end = n 39 | } else { 40 | this.end.next = n 41 | this.end = n 42 | } 43 | this.length++ 44 | } 45 | // Return the number of items in the queue 46 | func (this *Queue) Len() int { 47 | return this.length 48 | } 49 | // Return the first item in the queue without removing it 50 | func (this *Queue) Peek() interface{} { 51 | if this.length == 0 { 52 | return nil 53 | } 54 | return this.start.value 55 | } 56 | -------------------------------------------------------------------------------- /queue/queue_test.go: -------------------------------------------------------------------------------- 1 | package queue 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func Test(t *testing.T) { 8 | q := New() 9 | 10 | if q.Len() != 0 { 11 | t.Errorf("Length should be 0") 12 | } 13 | 14 | q.Enqueue(1) 15 | 16 | if q.Len() != 1 { 17 | t.Errorf("Length should be 1") 18 | } 19 | 20 | if q.Peek().(int) != 1 { 21 | t.Errorf("Enqueued value should be 1") 22 | } 23 | 24 | v := q.Dequeue() 25 | 26 | if v.(int) != 1 { 27 | t.Errorf("Dequeued value should be 1") 28 | } 29 | 30 | if q.Peek() != nil || q.Dequeue() != nil { 31 | t.Errorf("Empty queue should have no values") 32 | } 33 | 34 | q.Enqueue(1) 35 | q.Enqueue(2) 36 | 37 | if q.Len() != 2 { 38 | t.Errorf("Length should be 2") 39 | } 40 | 41 | if q.Peek().(int) != 1 { 42 | t.Errorf("First value should be 1") 43 | } 44 | 45 | q.Dequeue() 46 | 47 | if q.Peek().(int) != 2 { 48 | t.Errorf("Next value should be 2") 49 | } 50 | } -------------------------------------------------------------------------------- /set/set.go: -------------------------------------------------------------------------------- 1 | package set 2 | 3 | type ( 4 | Set struct { 5 | hash map[interface{}]nothing 6 | } 7 | 8 | nothing struct{} 9 | ) 10 | 11 | // Create a new set 12 | func New(initial ...interface{}) *Set { 13 | s := &Set{make(map[interface{}]nothing)} 14 | 15 | for _, v := range initial { 16 | s.Insert(v) 17 | } 18 | 19 | return s 20 | } 21 | 22 | // Find the difference between two sets 23 | func (this *Set) Difference(set *Set) *Set { 24 | n := make(map[interface{}]nothing) 25 | 26 | for k, _ := range this.hash { 27 | if _, exists := set.hash[k]; !exists { 28 | n[k] = nothing{} 29 | } 30 | } 31 | 32 | return &Set{n} 33 | } 34 | 35 | // Call f for each item in the set 36 | func (this *Set) Do(f func(interface{})) { 37 | for k, _ := range this.hash { 38 | f(k) 39 | } 40 | } 41 | 42 | // Test to see whether or not the element is in the set 43 | func (this *Set) Has(element interface{}) bool { 44 | _, exists := this.hash[element] 45 | return exists 46 | } 47 | 48 | // Add an element to the set 49 | func (this *Set) Insert(element interface{}) { 50 | this.hash[element] = nothing{} 51 | } 52 | 53 | // Find the intersection of two sets 54 | func (this *Set) Intersection(set *Set) *Set { 55 | n := make(map[interface{}]nothing) 56 | 57 | for k, _ := range this.hash { 58 | if _, exists := set.hash[k]; exists { 59 | n[k] = nothing{} 60 | } 61 | } 62 | 63 | return &Set{n} 64 | } 65 | 66 | // Return the number of items in the set 67 | func (this *Set) Len() int { 68 | return len(this.hash) 69 | } 70 | 71 | // Test whether or not this set is a proper subset of "set" 72 | func (this *Set) ProperSubsetOf(set *Set) bool { 73 | return this.SubsetOf(set) && this.Len() < set.Len() 74 | } 75 | 76 | // Remove an element from the set 77 | func (this *Set) Remove(element interface{}) { 78 | delete(this.hash, element) 79 | } 80 | 81 | // Test whether or not this set is a subset of "set" 82 | func (this *Set) SubsetOf(set *Set) bool { 83 | if this.Len() > set.Len() { 84 | return false 85 | } 86 | for k, _ := range this.hash { 87 | if _, exists := set.hash[k]; !exists { 88 | return false 89 | } 90 | } 91 | return true 92 | } 93 | 94 | // Find the union of two sets 95 | func (this *Set) Union(set *Set) *Set { 96 | n := make(map[interface{}]nothing) 97 | 98 | for k, _ := range this.hash { 99 | n[k] = nothing{} 100 | } 101 | for k, _ := range set.hash { 102 | n[k] = nothing{} 103 | } 104 | 105 | return &Set{n} 106 | } 107 | -------------------------------------------------------------------------------- /set/set_test.go: -------------------------------------------------------------------------------- 1 | package set 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func Test(t *testing.T) { 8 | s := New() 9 | 10 | s.Insert(5) 11 | 12 | if s.Len() != 1 { 13 | t.Errorf("Length should be 1") 14 | } 15 | 16 | if !s.Has(5) { 17 | t.Errorf("Membership test failed") 18 | } 19 | 20 | s.Remove(5) 21 | 22 | if s.Len() != 0 { 23 | t.Errorf("Length should be 0") 24 | } 25 | 26 | if s.Has(5) { 27 | t.Errorf("The set should be empty") 28 | } 29 | 30 | // Difference 31 | s1 := New(1,2,3,4,5,6) 32 | s2 := New(4,5,6) 33 | s3 := s1.Difference(s2) 34 | 35 | if s3.Len() != 3 { 36 | t.Errorf("Length should be 3") 37 | } 38 | 39 | if !(s3.Has(1) && s3.Has(2) && s3.Has(3)) { 40 | t.Errorf("Set should only contain 1, 2, 3") 41 | } 42 | 43 | // Intersection 44 | s3 = s1.Intersection(s2) 45 | if s3.Len() != 3 { 46 | t.Errorf("Length should be 3 after intersection") 47 | } 48 | 49 | if !(s3.Has(4) && s3.Has(5) && s3.Has(6)) { 50 | t.Errorf("Set should contain 4, 5, 6") 51 | } 52 | 53 | // Union 54 | s4 := New(7,8,9) 55 | s3 = s2.Union(s4) 56 | 57 | if s3.Len() != 6 { 58 | t.Errorf("Length should be 6 after union") 59 | } 60 | 61 | if !(s3.Has(7)) { 62 | t.Errorf("Set should contain 4, 5, 6, 7, 8, 9") 63 | } 64 | 65 | // Subset 66 | if !s1.SubsetOf(s1) { 67 | t.Errorf("set should be a subset of itself") 68 | } 69 | // Proper Subset 70 | if s1.ProperSubsetOf(s1) { 71 | t.Errorf("set should not be a subset of itself") 72 | } 73 | 74 | } 75 | -------------------------------------------------------------------------------- /skip/skip.go: -------------------------------------------------------------------------------- 1 | package skip 2 | 3 | import ( 4 | "fmt" 5 | "math/rand" 6 | "time" 7 | ) 8 | 9 | type ( 10 | node struct { 11 | next []*node 12 | key interface{} 13 | value interface{} 14 | } 15 | SkipList struct { 16 | root *node 17 | size int 18 | less func(interface{},interface{})bool 19 | gen *rand.Rand 20 | probability float64 21 | } 22 | ) 23 | // Create a new skip list 24 | func New(less func(interface{},interface{})bool) *SkipList { 25 | gen := rand.New(rand.NewSource(time.Now().UnixNano())) 26 | n := &node{make([]*node, 0),nil,nil} 27 | return &SkipList{n, 0, less, gen, 0.75} 28 | } 29 | func (this *SkipList) Do(f func(interface{}, interface{})bool) { 30 | if this.size == 0 { 31 | return 32 | } 33 | cur := this.root.next[0] 34 | for cur != nil { 35 | if !f(cur.key, cur.value) { 36 | break 37 | } 38 | cur = cur.next[0] 39 | } 40 | } 41 | // Get an item from the skip list 42 | func (this *SkipList) Get(key interface{}) interface{} { 43 | if this.size == 0 { 44 | return nil 45 | } 46 | 47 | cur := this.root 48 | // Start at the top 49 | for i := len(cur.next)-1; i >= 0; i-- { 50 | for this.less(cur.next[i].key, key) { 51 | cur = cur.next[i] 52 | } 53 | } 54 | cur = cur.next[0] 55 | 56 | if this.equals(cur.key, key) { 57 | return cur.value 58 | } 59 | 60 | return nil 61 | } 62 | // Insert a new item into the skip list 63 | func (this *SkipList) Insert(key interface{}, value interface{}) { 64 | prev := this.getPrevious(key) 65 | 66 | // Already in the list so just update the value 67 | if len(prev) > 0 && prev[0].next[0] != nil && this.equals(prev[0].next[0].key, key) { 68 | prev[0].next[0].value = value 69 | return 70 | } 71 | 72 | h := len(this.root.next) 73 | nh := this.pickHeight() 74 | n := &node{make([]*node, nh),key,value} 75 | 76 | // Higher than anything seen before, so tack it on top 77 | if nh > h { 78 | this.root.next = append(this.root.next, n) 79 | } 80 | 81 | // Update the previous nodes 82 | for i := 0; i < h && i < nh; i++ { 83 | n.next[i] = prev[i].next[i] 84 | prev[i].next[i] = n 85 | } 86 | 87 | this.size++ 88 | } 89 | // Get the length of the skip list 90 | func (this *SkipList) Len() int { 91 | return this.size 92 | } 93 | // Remove an item from the skip list 94 | func (this *SkipList) Remove(key interface{}) interface{} { 95 | prev := this.getPrevious(key) 96 | if len(prev) == 0 { 97 | return nil 98 | } 99 | cur := prev[0].next[0] 100 | 101 | // If we found it 102 | if cur != nil && this.equals(key, cur.key) { 103 | // Change all the linked lists 104 | for i := 0; i < len(prev); i++ { 105 | if prev[i] != nil && prev[i].next[i] != nil { 106 | prev[i].next[i] = cur.next[i] 107 | } 108 | } 109 | 110 | // Kill off the upper links if they're nil 111 | for i := len(this.root.next)-1; i>=0; i-- { 112 | if this.root.next[i] == nil { 113 | this.root.next = this.root.next[:i] 114 | } else { 115 | break 116 | } 117 | } 118 | 119 | this.size-- 120 | 121 | return cur.value 122 | } 123 | 124 | return nil 125 | } 126 | // String representation of the list 127 | func (this *SkipList) String() string { 128 | str := "{" 129 | if len(this.root.next) > 0 { 130 | cur := this.root.next[0] 131 | for cur != nil { 132 | str += fmt.Sprint(cur.key) 133 | str += ":" 134 | str += fmt.Sprint(cur.value) 135 | str += " " 136 | cur = cur.next[0] 137 | } 138 | } 139 | str += "}" 140 | 141 | return str 142 | } 143 | // Get a vertical list of nodes of all the things that occur 144 | // immediately before "key" 145 | func (this *SkipList) getPrevious(key interface{}) []*node { 146 | cur := this.root 147 | h := len(cur.next) 148 | nodes := make([]*node, h) 149 | for i := h-1; i >= 0; i-- { 150 | for cur.next[i] != nil && this.less(cur.next[i].key, key) { 151 | cur = cur.next[i] 152 | } 153 | nodes[i] = cur 154 | } 155 | return nodes 156 | } 157 | // Defines an equals method in terms of "less" 158 | func (this *SkipList) equals(a, b interface{}) bool { 159 | return !this.less(a,b) && !this.less(b,a) 160 | } 161 | // Pick a random height 162 | func (this *SkipList) pickHeight() int { 163 | h := 1 164 | for this.gen.Float64() > this.probability { 165 | h++ 166 | } 167 | if h > len(this.root.next) { 168 | return h + 1 169 | } 170 | return h 171 | } 172 | -------------------------------------------------------------------------------- /skip/skip_test.go: -------------------------------------------------------------------------------- 1 | package skip 2 | 3 | import ( 4 | //"fmt" 5 | "testing" 6 | ) 7 | 8 | func Test(t *testing.T) { 9 | sl := New(func(a,b interface{})bool { 10 | return a.(int) < b.(int) 11 | }) 12 | sl.Insert(1, 100) 13 | if sl.Len() != 1 { 14 | t.Errorf("expecting len 1") 15 | } 16 | sl.Insert(1, 1000) 17 | if sl.Len() != 1 { 18 | t.Errorf("expecting len 1") 19 | } 20 | if sl.Get(1).(int) != 1000 { 21 | t.Errorf("expecting sl[1] == 1000") 22 | } 23 | sl.Remove(1) 24 | if sl.Len() != 0 { 25 | t.Errorf("expecting len 0") 26 | } 27 | 28 | sl.Insert(2, 200) 29 | sl.Insert(1, 100) 30 | vs := make([]int, 0) 31 | sl.Do(func(k, v interface{}) bool { 32 | vs = append(vs, k.(int)) 33 | return true 34 | }) 35 | if len(vs) != 2 || vs[0] != 1 || vs[1] != 2 { 36 | t.Errorf("expecting sorted iteration of all keys") 37 | } 38 | } 39 | -------------------------------------------------------------------------------- /splay/splay.go: -------------------------------------------------------------------------------- 1 | package splay 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | type ( 8 | Any interface{} 9 | LessFunc func(interface{}, interface{}) bool 10 | VisitFunc func(interface{}) bool 11 | 12 | node struct { 13 | value Any 14 | parent, left, right *node 15 | } 16 | nodei struct { 17 | step int 18 | node *node 19 | prev *nodei 20 | } 21 | 22 | SplayTree struct { 23 | length int 24 | root *node 25 | less LessFunc 26 | } 27 | ) 28 | 29 | // Create a new splay tree, using the less function to determine the order. 30 | func New(less LessFunc) *SplayTree { 31 | return &SplayTree{0, nil, less} 32 | } 33 | 34 | // Get the first value from the collection. Returns nil if empty. 35 | func (this *SplayTree) First() Any { 36 | if this.length == 0 { 37 | return nil 38 | } 39 | 40 | n := this.root 41 | for n.left != nil { 42 | n = n.left 43 | } 44 | return n.value 45 | } 46 | 47 | // Get the last value from the collection. Returns nil if empty. 48 | func (this *SplayTree) Last() Any { 49 | if this.length == 0 { 50 | return nil 51 | } 52 | n := this.root 53 | for n.right != nil { 54 | n = n.right 55 | } 56 | return n.value 57 | } 58 | 59 | // Get an item from the splay tree 60 | func (this *SplayTree) Get(item Any) Any { 61 | if this.length == 0 { 62 | return nil 63 | } 64 | 65 | n := this.root 66 | for n != nil { 67 | if this.less(item, n.value) { 68 | n = n.left 69 | continue 70 | } 71 | 72 | if this.less(n.value, item) { 73 | n = n.right 74 | continue 75 | } 76 | 77 | this.splay(n) 78 | return n.value 79 | } 80 | return nil 81 | } 82 | func (this *SplayTree) Has(value Any) bool { 83 | return this.Get(value) != nil 84 | } 85 | func (this *SplayTree) Init() { 86 | this.length = 0 87 | this.root = nil 88 | } 89 | func (this *SplayTree) Add(value Any) { 90 | if this.length == 0 { 91 | this.root = &node{value, nil, nil, nil} 92 | this.length = 1 93 | return 94 | } 95 | 96 | n := this.root 97 | for { 98 | if this.less(value, n.value) { 99 | if n.left == nil { 100 | n.left = &node{value, n, nil, nil} 101 | this.length++ 102 | n = n.left 103 | break 104 | } 105 | n = n.left 106 | continue 107 | } 108 | 109 | if this.less(n.value, value) { 110 | if n.right == nil { 111 | n.right = &node{value, n, nil, nil} 112 | this.length++ 113 | n = n.right 114 | break 115 | } 116 | n = n.right 117 | continue 118 | } 119 | 120 | n.value = value 121 | break 122 | } 123 | this.splay(n) 124 | } 125 | func (this *SplayTree) PreOrder(visit VisitFunc) { 126 | if this.length == 1 { 127 | return 128 | } 129 | i := &nodei{0, this.root, nil} 130 | for i != nil { 131 | switch i.step { 132 | // Value 133 | case 0: 134 | i.step++ 135 | if !visit(i.node.value) { 136 | break 137 | } 138 | // Left 139 | case 1: 140 | i.step++ 141 | if i.node.left != nil { 142 | i = &nodei{0, i.node.left, i} 143 | } 144 | // Right 145 | case 2: 146 | i.step++ 147 | if i.node.right != nil { 148 | i = &nodei{0, i.node.right, i} 149 | } 150 | default: 151 | i = i.prev 152 | } 153 | } 154 | } 155 | func (this *SplayTree) InOrder(visit VisitFunc) { 156 | if this.length == 1 { 157 | return 158 | } 159 | i := &nodei{0, this.root, nil} 160 | for i != nil { 161 | switch i.step { 162 | // Left 163 | case 0: 164 | i.step++ 165 | if i.node.left != nil { 166 | i = &nodei{0, i.node.left, i} 167 | } 168 | // Value 169 | case 1: 170 | i.step++ 171 | if !visit(i.node.value) { 172 | break 173 | } 174 | // Right 175 | case 2: 176 | i.step++ 177 | if i.node.right != nil { 178 | i = &nodei{0, i.node.right, i} 179 | } 180 | default: 181 | i = i.prev 182 | } 183 | } 184 | } 185 | func (this *SplayTree) PostOrder(visit VisitFunc) { 186 | if this.length == 1 { 187 | return 188 | } 189 | i := &nodei{0, this.root, nil} 190 | for i != nil { 191 | switch i.step { 192 | // Left 193 | case 0: 194 | i.step++ 195 | if i.node.left != nil { 196 | i = &nodei{0, i.node.left, i} 197 | } 198 | // Right 199 | case 1: 200 | i.step++ 201 | if i.node.right != nil { 202 | i = &nodei{0, i.node.right, i} 203 | } 204 | // Value 205 | case 2: 206 | i.step++ 207 | if !visit(i.node.value) { 208 | break 209 | } 210 | default: 211 | i = i.prev 212 | } 213 | } 214 | } 215 | func (this *SplayTree) Do(visit VisitFunc) { 216 | this.InOrder(visit) 217 | } 218 | func (this *SplayTree) Len() int { 219 | return this.length 220 | } 221 | func (this *SplayTree) Remove(value Any) { 222 | if this.length == 0 { 223 | return 224 | } 225 | 226 | n := this.root 227 | for n != nil { 228 | if this.less(value, n.value) { 229 | n = n.left 230 | continue 231 | } 232 | if this.less(n.value, value) { 233 | n = n.right 234 | continue 235 | } 236 | 237 | // First splay the parent node 238 | if n.parent != nil { 239 | this.splay(n.parent) 240 | } 241 | 242 | // No children 243 | if n.left == nil && n.right == nil { 244 | // guess we're the root node 245 | if n.parent == nil { 246 | this.root = nil 247 | break 248 | } 249 | if n.parent.left == n { 250 | n.parent.left = nil 251 | } else { 252 | n.parent.right = nil 253 | } 254 | } else if n.left == nil { 255 | // root node 256 | if n.parent == nil { 257 | this.root = n.right 258 | break 259 | } 260 | if n.parent.left == n { 261 | n.parent.left = n.right 262 | } else { 263 | n.parent.right = n.right 264 | } 265 | } else if n.right == nil { 266 | // root node 267 | if n.parent == nil { 268 | this.root = n.left 269 | break 270 | } 271 | if n.parent.left == n { 272 | n.parent.left = n.left 273 | } else { 274 | n.parent.right = n.left 275 | } 276 | } else { 277 | // find the successor 278 | s := n.right 279 | for s.left != nil { 280 | s = s.left 281 | } 282 | 283 | np := n.parent 284 | nl := n.left 285 | nr := n.right 286 | 287 | sp := s.parent 288 | sr := s.right 289 | 290 | // Update parent 291 | s.parent = np 292 | if np == nil { 293 | this.root = s 294 | } else { 295 | if np.left == n { 296 | np.left = s 297 | } else { 298 | np.right = s 299 | } 300 | } 301 | 302 | // Update left 303 | s.left = nl 304 | s.left.parent = s 305 | 306 | // Update right 307 | if nr != s { 308 | s.right = nr 309 | s.right.parent = s 310 | } 311 | 312 | // Update successor parent 313 | if sp.left == s { 314 | sp.left = sr 315 | } else { 316 | sp.right = sr 317 | } 318 | } 319 | 320 | break 321 | } 322 | 323 | if n != nil { 324 | this.length-- 325 | } 326 | } 327 | func (this *SplayTree) String() string { 328 | if this.length == 0 { 329 | return "{}" 330 | } 331 | return this.root.String() 332 | } 333 | 334 | // Splay a node in the tree (send it to the top) 335 | func (this *SplayTree) splay(n *node) { 336 | // Already root, nothing to do 337 | if n.parent == nil { 338 | this.root = n 339 | return 340 | } 341 | 342 | p := n.parent 343 | g := p.parent 344 | 345 | // Zig 346 | if p == this.root { 347 | if n == p.left { 348 | p.rotateRight() 349 | } else { 350 | p.rotateLeft() 351 | } 352 | } else { 353 | // Zig-zig 354 | if n == p.left && p == g.left { 355 | g.rotateRight() 356 | p.rotateRight() 357 | } else if n == p.right && p == g.right { 358 | g.rotateLeft() 359 | p.rotateLeft() 360 | // Zig-zag 361 | } else if n == p.right && p == g.left { 362 | p.rotateLeft() 363 | g.rotateRight() 364 | } else if n == p.left && p == g.right { 365 | p.rotateRight() 366 | g.rotateLeft() 367 | } 368 | } 369 | this.splay(n) 370 | } 371 | 372 | // Swap two nodes in the tree 373 | func (this *SplayTree) swap(n1, n2 *node) { 374 | p1 := n1.parent 375 | l1 := n1.left 376 | r1 := n1.right 377 | 378 | p2 := n2.parent 379 | l2 := n2.left 380 | r2 := n2.right 381 | 382 | // Update node links 383 | n1.parent = p2 384 | n1.left = l2 385 | n1.right = r2 386 | 387 | n2.parent = p1 388 | n2.left = l1 389 | n2.right = r1 390 | 391 | // Update parent links 392 | if p1 != nil { 393 | if p1.left == n1 { 394 | p1.left = n2 395 | } else { 396 | p1.right = n2 397 | } 398 | } 399 | if p2 != nil { 400 | if p2.left == n2 { 401 | p2.left = n1 402 | } else { 403 | p2.right = n1 404 | } 405 | } 406 | 407 | if n1 == this.root { 408 | this.root = n2 409 | } else if n2 == this.root { 410 | this.root = n1 411 | } 412 | } 413 | 414 | // Node methods 415 | func (this *node) String() string { 416 | str := "{" + fmt.Sprint(this.value) + "|" 417 | if this.left != nil { 418 | str += this.left.String() 419 | } 420 | str += "|" 421 | if this.right != nil { 422 | str += this.right.String() 423 | } 424 | str += "}" 425 | return str 426 | } 427 | func (this *node) rotateLeft() { 428 | parent := this.parent 429 | pivot := this.right 430 | child := pivot.left 431 | 432 | if pivot == nil { 433 | return 434 | } 435 | 436 | // Update the parent 437 | if parent != nil { 438 | if parent.left == this { 439 | parent.left = pivot 440 | } else { 441 | parent.right = pivot 442 | } 443 | } 444 | 445 | // Update the pivot 446 | pivot.parent = parent 447 | pivot.left = this 448 | 449 | // Update the child 450 | if child != nil { 451 | child.parent = this 452 | } 453 | 454 | // Update this 455 | this.parent = pivot 456 | this.right = child 457 | } 458 | func (this *node) rotateRight() { 459 | parent := this.parent 460 | pivot := this.left 461 | child := pivot.right 462 | 463 | if pivot == nil { 464 | return 465 | } 466 | 467 | // Update the parent 468 | if parent != nil { 469 | if parent.left == this { 470 | parent.left = pivot 471 | } else { 472 | parent.right = pivot 473 | } 474 | } 475 | 476 | // Update the pivot 477 | pivot.parent = parent 478 | pivot.right = this 479 | 480 | if child != nil { 481 | child.parent = this 482 | } 483 | 484 | // Update this 485 | this.parent = pivot 486 | this.left = child 487 | } 488 | -------------------------------------------------------------------------------- /splay/splay_test.go: -------------------------------------------------------------------------------- 1 | package splay 2 | 3 | import ( 4 | //"fmt" 5 | "testing" 6 | ) 7 | 8 | func Test(t *testing.T) { 9 | tree := New(func(a,b interface{})bool { 10 | return a.(string) < b.(string) 11 | }) 12 | 13 | tree.Insert("d", 4) 14 | tree.Insert("b", 2) 15 | tree.Insert("a", 1) 16 | tree.Insert("c", 3) 17 | 18 | if tree.Len() != 4 { 19 | t.Errorf("expecting len 4") 20 | } 21 | 22 | tree.Remove("b") 23 | 24 | if tree.Len() != 3 { 25 | t.Errorf("expecting len 3") 26 | } 27 | } -------------------------------------------------------------------------------- /stack/stack.go: -------------------------------------------------------------------------------- 1 | package stack 2 | 3 | type ( 4 | Stack struct { 5 | top *node 6 | length int 7 | } 8 | node struct { 9 | value interface{} 10 | prev *node 11 | } 12 | ) 13 | // Create a new stack 14 | func New() *Stack { 15 | return &Stack{nil,0} 16 | } 17 | // Return the number of items in the stack 18 | func (this *Stack) Len() int { 19 | return this.length 20 | } 21 | // View the top item on the stack 22 | func (this *Stack) Peek() interface{} { 23 | if this.length == 0 { 24 | return nil 25 | } 26 | return this.top.value 27 | } 28 | // Pop the top item of the stack and return it 29 | func (this *Stack) Pop() interface{} { 30 | if this.length == 0 { 31 | return nil 32 | } 33 | 34 | n := this.top 35 | this.top = n.prev 36 | this.length-- 37 | return n.value 38 | } 39 | // Push a value onto the top of the stack 40 | func (this *Stack) Push(value interface{}) { 41 | n := &node{value,this.top} 42 | this.top = n 43 | this.length++ 44 | } -------------------------------------------------------------------------------- /stack/stack_test.go: -------------------------------------------------------------------------------- 1 | package stack 2 | 3 | import ( 4 | "testing" 5 | ) 6 | 7 | func Test(t *testing.T) { 8 | s := New() 9 | 10 | if s.Len() != 0 { 11 | t.Errorf("Length of an empty stack should be 0") 12 | } 13 | 14 | s.Push(1) 15 | 16 | if s.Len() != 1 { 17 | t.Errorf("Length should be 0") 18 | } 19 | 20 | if s.Peek().(int) != 1 { 21 | t.Errorf("Top item on the stack should be 1") 22 | } 23 | 24 | if s.Pop().(int) != 1 { 25 | t.Errorf("Top item should have been 1") 26 | } 27 | 28 | if s.Len() != 0 { 29 | t.Errorf("Stack should be empty") 30 | } 31 | 32 | s.Push(1) 33 | s.Push(2) 34 | 35 | if s.Len() != 2 { 36 | t.Errorf("Length should be 2") 37 | } 38 | 39 | if s.Peek().(int) != 2 { 40 | t.Errorf("Top of the stack should be 2") 41 | } 42 | } -------------------------------------------------------------------------------- /trie/trie.go: -------------------------------------------------------------------------------- 1 | package trie 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | type ( 8 | Trie struct { 9 | root *node 10 | size int 11 | } 12 | node struct { 13 | key interface{} 14 | value interface{} 15 | next [256]*node 16 | } 17 | iterator struct { 18 | step int 19 | node *node 20 | prev *iterator 21 | } 22 | ) 23 | 24 | func toBytes(obj interface{}) []byte { 25 | switch o := obj.(type) { 26 | case []byte: 27 | return o 28 | case string: 29 | return []byte(o) 30 | } 31 | return []byte(fmt.Sprint(obj)) 32 | } 33 | 34 | func New() *Trie { 35 | return &Trie{nil,0} 36 | } 37 | func (this *Trie) Do(handler func(interface{},interface{})bool) { 38 | if this.size > 0 { 39 | this.root.do(handler) 40 | } 41 | } 42 | func (this *Trie) Get(key interface{}) interface{} { 43 | if this.size == 0 { 44 | return nil 45 | } 46 | 47 | bs := toBytes(key) 48 | cur := this.root 49 | for i := 0; i < len(bs); i++ { 50 | if cur.next[bs[i]] != nil { 51 | cur = cur.next[bs[i]] 52 | } else { 53 | return nil 54 | } 55 | } 56 | return cur.value 57 | } 58 | func (this *Trie) Has(key interface{}) bool { 59 | return this.Get(key) != nil 60 | } 61 | func (this *Trie) Init() { 62 | this.root = nil 63 | this.size = 0 64 | } 65 | func (this *Trie) Insert(key interface{}, value interface{}) { 66 | if this.size == 0 { 67 | this.root = newNode() 68 | } 69 | 70 | bs := toBytes(key) 71 | cur := this.root 72 | for i := 0; i < len(bs); i++ { 73 | if cur.next[bs[i]] != nil { 74 | cur = cur.next[bs[i]] 75 | } else { 76 | cur.next[bs[i]] = newNode() 77 | cur = cur.next[bs[i]] 78 | } 79 | } 80 | if cur.key == nil { 81 | this.size++ 82 | } 83 | cur.key = key 84 | cur.value = value 85 | } 86 | func (this *Trie) Len() int { 87 | return this.size 88 | } 89 | func (this *Trie) Remove(key interface{}) interface{} { 90 | if this.size == 0 { 91 | return nil 92 | } 93 | bs := toBytes(key) 94 | cur := this.root 95 | 96 | for i := 0; i < len(bs); i++ { 97 | if cur.next[bs[i]] != nil { 98 | cur = cur.next[bs[i]] 99 | } else { 100 | return nil 101 | } 102 | } 103 | 104 | // TODO: cleanup dead nodes 105 | 106 | val := cur.value 107 | 108 | if cur.value != nil { 109 | this.size-- 110 | cur.value = nil 111 | cur.key = nil 112 | } 113 | return val 114 | } 115 | func (this *Trie) String() string { 116 | str := "{" 117 | i := 0 118 | this.Do(func(k, v interface{}) bool { 119 | if i > 0 { 120 | str += ", " 121 | } 122 | str += fmt.Sprint(k, ":", v) 123 | i++ 124 | return true 125 | }) 126 | str += "}" 127 | return str 128 | } 129 | 130 | func newNode() *node { 131 | var next [256]*node 132 | return &node{nil,nil,next} 133 | } 134 | func (this *node) do(handler func(interface{}, interface{}) bool) bool { 135 | for i := 0; i < 256; i++ { 136 | if this.next[i] != nil { 137 | if this.next[i].key != nil { 138 | if !handler(this.next[i].key, this.next[i].value) { 139 | return false 140 | } 141 | } 142 | if !this.next[i].do(handler) { 143 | return false 144 | } 145 | } 146 | } 147 | return true 148 | } -------------------------------------------------------------------------------- /trie/trie_test.go: -------------------------------------------------------------------------------- 1 | package trie 2 | 3 | import ( 4 | //"fmt" 5 | "testing" 6 | ) 7 | 8 | func Test(t *testing.T) { 9 | x := New() 10 | x.Insert(1, 100) 11 | if x.Len() != 1 { 12 | t.Errorf("expected len 1") 13 | } 14 | if x.Get(1).(int) != 100 { 15 | t.Errorf("expected to get 100 for 1") 16 | } 17 | x.Remove(1) 18 | if x.Len() != 0 { 19 | t.Errorf("expected len 0") 20 | } 21 | x.Insert(2, 200) 22 | x.Insert(1, 100) 23 | vs := make([]int, 0) 24 | x.Do(func(k, v interface{}) bool { 25 | vs = append(vs, k.(int)) 26 | return true 27 | }) 28 | if len(vs) != 2 || vs[0] != 1 || vs[1] != 2 { 29 | t.Errorf("expected in order traversal") 30 | } 31 | } -------------------------------------------------------------------------------- /tst/tst.go: -------------------------------------------------------------------------------- 1 | package tst 2 | 3 | import ( 4 | "fmt" 5 | ) 6 | 7 | type ( 8 | Node struct { 9 | key byte 10 | value interface{} 11 | left, middle, right *Node 12 | } 13 | NodeIterator struct { 14 | step int 15 | node *Node 16 | prev *NodeIterator 17 | } 18 | TernarySearchTree struct { 19 | length int 20 | root *Node 21 | } 22 | ) 23 | 24 | // Create a new ternary search tree 25 | func New() *TernarySearchTree { 26 | tree := &TernarySearchTree{} 27 | tree.Init() 28 | return tree 29 | } 30 | // Iterate over the collection 31 | func (this *TernarySearchTree) Do(callback func(string, interface{})bool) { 32 | if this.Len() == 0 { 33 | return 34 | } 35 | bs := []byte{} 36 | i := &NodeIterator{0,this.root,nil} 37 | for i != nil { 38 | switch i.step { 39 | // Left 40 | case 0: 41 | i.step++ 42 | if i.node.left != nil { 43 | i = &NodeIterator{0,i.node.left,i} 44 | continue 45 | } 46 | // Value 47 | case 1: 48 | i.step++ 49 | if i.node.key > 0 { 50 | bs = append(bs, i.node.key) 51 | } 52 | if i.node.value != nil { 53 | if !callback(string(bs), i.node.value) { 54 | return 55 | } 56 | continue 57 | } 58 | // Middle 59 | case 2: 60 | i.step++ 61 | if i.node.middle != nil { 62 | i = &NodeIterator{0,i.node.middle,i} 63 | continue 64 | } 65 | // Right 66 | case 3: 67 | if len(bs) > 0 { 68 | bs = bs[:len(bs)-1] 69 | } 70 | i.step++ 71 | if i.node.right != nil { 72 | i = &NodeIterator{0,i.node.right,i} 73 | continue 74 | } 75 | // Backtrack 76 | case 4: 77 | i = i.prev 78 | } 79 | } 80 | } 81 | // Get the value at the specified key. Returns nil if not found. 82 | func (this *TernarySearchTree) Get(key string) interface{} { 83 | if this.length == 0 { 84 | return nil 85 | } 86 | 87 | node := this.root 88 | bs := []byte(key) 89 | for i := 0; i < len(bs); { 90 | b := bs[i] 91 | if b > node.key { 92 | if node.right == nil { 93 | return nil 94 | } 95 | node = node.right 96 | } else if (b < node.key) { 97 | if node.left == nil { 98 | return nil 99 | } 100 | node = node.left 101 | } else { 102 | i++ 103 | if i < len(bs) { 104 | if node.middle == nil { 105 | return nil 106 | } 107 | node = node.middle 108 | } else { 109 | break 110 | } 111 | } 112 | } 113 | return node.value 114 | } 115 | func (this *TernarySearchTree) GetLongestPrefix(key string) interface{} { 116 | if this.length == 0 { 117 | return nil 118 | } 119 | 120 | n := this.root 121 | v := n.value 122 | bs := []byte(key) 123 | for i := 0; i < len(bs); { 124 | b := bs[i] 125 | if n.value != nil { 126 | v = n.value 127 | } 128 | if b > n.key { 129 | if n.right == nil { 130 | break 131 | } 132 | n = n.right 133 | } else if b < n.key { 134 | if n.left == nil { 135 | break 136 | } 137 | n = n.left 138 | } else { 139 | i++ 140 | if i < len(bs) { 141 | if n.middle == nil { 142 | break 143 | } 144 | n = n.middle 145 | } else { 146 | break 147 | } 148 | } 149 | } 150 | if n.value != nil { 151 | v = n.value 152 | } 153 | return v 154 | } 155 | // Test to see whether or not the given key is contained in the tree. 156 | func (this *TernarySearchTree) Has(key string) bool { 157 | return this.Get(key) != nil 158 | } 159 | // Initialize the tree (reset it so that it's empty). New will do this for you. 160 | func (this *TernarySearchTree) Init() { 161 | this.length = 0 162 | this.root = nil 163 | } 164 | // Insert a new key value pair into the collection 165 | func (this *TernarySearchTree) Insert(key string, value interface{}) { 166 | // If the value is nil then remove this key from the collection 167 | if value == nil { 168 | this.Remove(key) 169 | return 170 | } 171 | 172 | if this.length == 0 { 173 | this.root = &Node{0,nil,nil,nil,nil} 174 | } 175 | 176 | t := this.root 177 | bs := []byte(key) 178 | for i := 0; i < len(bs); { 179 | b := bs[i] 180 | if b > t.key { 181 | if t.right == nil { 182 | t.right = &Node{b,nil,nil,nil,nil} 183 | } 184 | t = t.right 185 | } else if b < t.key { 186 | if t.left == nil { 187 | t.left = &Node{b,nil,nil,nil,nil} 188 | } 189 | t = t.left 190 | } else { 191 | i++ 192 | if i < len(bs) { 193 | if t.middle == nil { 194 | t.middle = &Node{bs[i],nil,nil,nil,nil} 195 | } 196 | t = t.middle 197 | } 198 | } 199 | } 200 | 201 | if t.value == nil { 202 | this.length++ 203 | } 204 | t.value = value 205 | } 206 | // Get the number of items stored in the tree 207 | func (this *TernarySearchTree) Len() int { 208 | return this.length 209 | } 210 | // Remove a key from the collection 211 | func (this *TernarySearchTree) Remove(key string) interface{} { 212 | if this.length == 0 { 213 | return nil 214 | } 215 | 216 | var remove *Node 217 | var direction int 218 | 219 | t := this.root 220 | bs := []byte(key) 221 | for i := 0; i < len(bs); { 222 | b := bs[i] 223 | if b > t.key { 224 | // Not in the collection 225 | if t.right == nil { 226 | return nil 227 | } 228 | // This is a branch so we have to keep it 229 | remove = t 230 | direction = 1 231 | // Move to the next node 232 | t = t.right 233 | } else if b < t.key { 234 | // Not in the collection 235 | if t.left == nil { 236 | return nil 237 | } 238 | // This is a branch so we have to keep it 239 | remove = t 240 | direction = -1 241 | // Move to the next node 242 | t = t.left 243 | } else { 244 | i++ 245 | if i < len(bs) { 246 | // Not in the collection 247 | if t.middle == nil { 248 | return nil 249 | } 250 | // Has a value so we need to keep at least this much 251 | if t.value != nil { 252 | remove = t 253 | direction = 0 254 | } 255 | // Move to the next node 256 | t = t.middle 257 | } 258 | } 259 | } 260 | 261 | // If this was the only item in the tree, set the root pointer to nil 262 | if this.length == 1 { 263 | this.root = nil 264 | } else { 265 | if direction == -1 { 266 | remove.left = nil 267 | } else if direction == 0 { 268 | remove.middle = nil 269 | } else { 270 | remove.right = nil 271 | } 272 | } 273 | this.length-- 274 | return t.value 275 | } 276 | func (this *TernarySearchTree) String() string { 277 | if this.length == 0 { 278 | return "{}" 279 | } 280 | 281 | return this.root.String() 282 | } 283 | // Dump the tree to a string for easier debugging 284 | func (this *Node) String() string { 285 | str := "{" + string(this.key) 286 | if this.value != nil { 287 | str += ":" + fmt.Sprint(this.value) 288 | } 289 | if this.left != nil { 290 | str += this.left.String() 291 | } else { 292 | str += " " 293 | } 294 | if this.middle != nil { 295 | str += this.middle.String() 296 | } else { 297 | str += " " 298 | } 299 | if this.right != nil { 300 | str += this.right.String() 301 | } else { 302 | str += " " 303 | } 304 | str += "}" 305 | return str 306 | } 307 | -------------------------------------------------------------------------------- /tst/tst_test.go: -------------------------------------------------------------------------------- 1 | package tst 2 | 3 | import ( 4 | //"fmt" 5 | "math/rand" 6 | "testing" 7 | ) 8 | 9 | func randomString() string { 10 | n := 3 + rand.Intn(10) 11 | bs := make([]byte, n) 12 | for i := 0; i