github.com/mymmsc/gox@v1.3.33/util/README-gods.md (about) 1 # GoDS (Go Data Structures) 2 3 Implementation of various data structures and algorithms in Go. 4 5 ## Data Structures 6 7 - [Containers](#containers) 8 - [Lists](#lists) 9 - [ArrayList](#arraylist) 10 - [SinglyLinkedList](#singlylinkedlist) 11 - [DoublyLinkedList](#doublylinkedlist) 12 - [Sets](#sets) 13 - [HashSet](#hashset) 14 - [TreeSet](#treeset) 15 - [LinkedHashSet](#linkedhashset) 16 - [Stacks](#stacks) 17 - [LinkedListStack](#linkedliststack) 18 - [ArrayStack](#arraystack) 19 - [Maps](#maps) 20 - [HashMap](#hashmap) 21 - [TreeMap](#treemap) 22 - [LinkedHashMap](#linkedhashmap) 23 - [HashBidiMap](#hashbidimap) 24 - [TreeBidiMap](#treebidimap) 25 - [Trees](#trees) 26 - [RedBlackTree](#redblacktree) 27 - [AVLTree](#avltree) 28 - [BTree](#btree) 29 - [BinaryHeap](#binaryheap) 30 - [Functions](#functions) 31 - [Comparator](#comparator) 32 - [Iterator](#iterator) 33 - [IteratorWithIndex](#iteratorwithindex) 34 - [IteratorWithKey](#iteratorwithkey) 35 - [ReverseIteratorWithIndex](#reverseiteratorwithindex) 36 - [ReverseIteratorWithKey](#reverseiteratorwithkey) 37 - [Enumerable](#enumerable) 38 - [EnumerableWithIndex](#enumerablewithindex) 39 - [EnumerableWithKey](#enumerablewithkey) 40 - [Serialization](#serialization) 41 - [JSONSerializer](#jsonserializer) 42 - [JSONDeserializer](#jsondeserializer) 43 - [Sort](#sort) 44 - [Container](#container) 45 - [Appendix](#appendix) 46 47 ## Containers 48 49 All data structures implement the container interface with the following methods: 50 51 ```go 52 type Container interface { 53 Empty() bool 54 Size() int 55 Clear() 56 Values() []interface{} 57 } 58 ``` 59 60 Containers are either ordered or unordered. All ordered containers provide [stateful iterators](#iterator) and some of 61 them allow [enumerable functions](#enumerable). 62 63 | **Data** | **Structure** | **Ordered** | **[Iterator](#iterator)** | **[Enumerable](#enumerable)** | **Referenced 64 by** | 65 | :--- | :--- | :---: | :---: | :---: | :---: | 66 | [Lists](#lists) | 67 | | [ArrayList](#arraylist) | yes | yes* | yes | index | 68 | | [SinglyLinkedList](#singlylinkedlist) | yes | yes | yes | index | 69 | | [DoublyLinkedList](#doublylinkedlist) | yes | yes* | yes | index | 70 | [Sets](#sets) | 71 | | [HashSet](#hashset) | no | no | no | index | 72 | | [TreeSet](#treeset) | yes | yes* | yes | index | 73 | | [LinkedHashSet](#linkedhashset) | yes | yes* | yes | index | 74 | [Stacks](#stacks) | 75 | | [LinkedListStack](#linkedliststack) | yes | yes | no | index | 76 | | [ArrayStack](#arraystack) | yes | yes* | no | index | 77 | [Maps](#maps) | 78 | | [HashMap](#hashmap) | no | no | no | key | 79 | | [TreeMap](#treemap) | yes | yes* | yes | key | 80 | | [LinkedHashMap](#linkedhashmap) | yes | yes* | yes | key | 81 | | [HashBidiMap](#hashbidimap) | no | no | no | key* | 82 | | [TreeBidiMap](#treebidimap) | yes | yes* | yes | key* | 83 | [Trees](#trees) | 84 | | [RedBlackTree](#redblacktree) | yes | yes* | no | key | 85 | | [AVLTree](#avltree) | yes | yes* | no | key | 86 | | [BTree](#btree) | yes | yes* | no | key | 87 | | [BinaryHeap](#binaryheap) | yes | yes* | no | index | 88 | | | | <sub><sup>*reversible</sup></sub> | | <sub><sup>*bidirectional</sup></sub> | 89 90 ### Lists 91 92 A list is a data structure that stores values and may have repeated values. 93 94 Implements [Container](#containers) interface. 95 96 ```go 97 type List interface { 98 Get(index int) (interface{}, bool) 99 Remove(index int) 100 Add(values ...interface{}) 101 Contains(values ...interface{}) bool 102 Sort(comparator utils.Comparator) 103 Swap(index1, index2 int) 104 Insert(index int, values ...interface{}) 105 Set(index int, value interface{}) 106 107 containers.Container 108 // Empty() bool 109 // Size() int 110 // Clear() 111 // Values() []interface{} 112 } 113 ``` 114 115 #### ArrayList 116 117 A [list](#lists) backed by a dynamic array that grows and shrinks implicitly. 118 119 Implements [List](#lists), [IteratorWithIndex](#iteratorwithindex), [EnumerableWithIndex](#enumerablewithindex) 120 , [JSONSerializer](#jsonserializer) and [JSONDeserializer](#jsondeserializer) interfaces. 121 122 ```go 123 package main 124 125 import ( 126 "github.com/mymmsc/gox/util/lists/arraylist" 127 "github.com/mymmsc/gox/util/utils" 128 ) 129 130 func main() { 131 list := arraylist.New() 132 list.Add("a") // ["a"] 133 list.Add("c", "b") // ["a","c","b"] 134 list.Sort(utils.StringComparator) // ["a","b","c"] 135 _, _ = list.Get(0) // "a",true 136 _, _ = list.Get(100) // nil,false 137 _ = list.Contains("a", "b", "c") // true 138 _ = list.Contains("a", "b", "c", "d") // false 139 list.Swap(0, 1) // ["b","a",c"] 140 list.Remove(2) // ["b","a"] 141 list.Remove(1) // ["b"] 142 list.Remove(0) // [] 143 list.Remove(0) // [] (ignored) 144 _ = list.Empty() // true 145 _ = list.Size() // 0 146 list.Add("a") // ["a"] 147 list.Clear() // [] 148 list.Insert(0, "b") // ["b"] 149 list.Insert(0, "a") // ["a","b"] 150 } 151 ``` 152 153 #### SinglyLinkedList 154 155 A [list](#lists) where each element points to the next element in the list. 156 157 Implements [List](#lists), [IteratorWithIndex](#iteratorwithindex), [EnumerableWithIndex](#enumerablewithindex) 158 , [JSONSerializer](#jsonserializer) and [JSONDeserializer](#jsondeserializer) interfaces. 159 160 ```go 161 package main 162 163 import ( 164 sll "github.com/mymmsc/gox/util/lists/singlylinkedlist" 165 "github.com/mymmsc/gox/util/utils" 166 ) 167 168 func main() { 169 list := sll.New() 170 list.Add("a") // ["a"] 171 list.Add("c", "b") // ["a","c","b"] 172 list.Sort(utils.StringComparator) // ["a","b","c"] 173 _, _ = list.Get(0) // "a",true 174 _, _ = list.Get(100) // nil,false 175 _ = list.Contains("a", "b", "c") // true 176 _ = list.Contains("a", "b", "c", "d") // false 177 list.Swap(0, 1) // ["b","a",c"] 178 list.Remove(2) // ["b","a"] 179 list.Remove(1) // ["b"] 180 list.Remove(0) // [] 181 list.Remove(0) // [] (ignored) 182 _ = list.Empty() // true 183 _ = list.Size() // 0 184 list.Add("a") // ["a"] 185 list.Clear() // [] 186 list.Insert(0, "b") // ["b"] 187 list.Insert(0, "a") // ["a","b"] 188 } 189 ``` 190 191 #### DoublyLinkedList 192 193 A [list](#lists) where each element points to the next and previous elements in the list. 194 195 Implements [List](#lists), [IteratorWithIndex](#iteratorwithindex), [EnumerableWithIndex](#enumerablewithindex) 196 , [JSONSerializer](#jsonserializer) and [JSONDeserializer](#jsondeserializer) interfaces. 197 198 ```go 199 package main 200 201 import ( 202 dll "github.com/mymmsc/gox/util/lists/doublylinkedlist" 203 "github.com/mymmsc/gox/util/utils" 204 ) 205 206 func main() { 207 list := dll.New() 208 list.Add("a") // ["a"] 209 list.Add("c", "b") // ["a","c","b"] 210 list.Sort(utils.StringComparator) // ["a","b","c"] 211 _, _ = list.Get(0) // "a",true 212 _, _ = list.Get(100) // nil,false 213 _ = list.Contains("a", "b", "c") // true 214 _ = list.Contains("a", "b", "c", "d") // false 215 list.Swap(0, 1) // ["b","a",c"] 216 list.Remove(2) // ["b","a"] 217 list.Remove(1) // ["b"] 218 list.Remove(0) // [] 219 list.Remove(0) // [] (ignored) 220 _ = list.Empty() // true 221 _ = list.Size() // 0 222 list.Add("a") // ["a"] 223 list.Clear() // [] 224 list.Insert(0, "b") // ["b"] 225 list.Insert(0, "a") // ["a","b"] 226 } 227 ``` 228 229 ### Sets 230 231 A set is a data structure that can store elements and has no repeated values. It is a computer implementation of the 232 mathematical concept of a finite set. Unlike most other collection types, rather than retrieving a specific element from 233 a set, one typically tests an element for membership in a set. This structure is often used to ensure that no duplicates 234 are present in a container. 235 236 Implements [Container](#containers) interface. 237 238 ```go 239 type Set interface { 240 Add(elements ...interface{}) 241 Remove(elements ...interface{}) 242 Contains(elements ...interface{}) bool 243 244 containers.Container 245 // Empty() bool 246 // Size() int 247 // Clear() 248 // Values() []interface{} 249 } 250 ``` 251 252 #### HashSet 253 254 A [set](#sets) backed by a hash table (actually a Go's map). It makes no guarantees as to the iteration order of the 255 set. 256 257 Implements [Set](#sets), [JSONSerializer](#jsonserializer) and [JSONDeserializer](#jsondeserializer) interfaces. 258 259 ```go 260 package main 261 262 import "github.com/mymmsc/gox/util/sets/hashset" 263 264 func main() { 265 set := hashset.New() // empty 266 set.Add(1) // 1 267 set.Add(2, 2, 3, 4, 5) // 3, 1, 2, 4, 5 (random order, duplicates ignored) 268 set.Remove(4) // 5, 3, 2, 1 (random order) 269 set.Remove(2, 3) // 1, 5 (random order) 270 set.Contains(1) // true 271 set.Contains(1, 5) // true 272 set.Contains(1, 6) // false 273 _ = set.Values() // []int{5,1} (random order) 274 set.Clear() // empty 275 set.Empty() // true 276 set.Size() // 0 277 } 278 ``` 279 280 #### TreeSet 281 282 A [set](#sets) backed by a [red-black tree](#redblacktree) to keep the elements ordered with respect to 283 the [comparator](#comparator). 284 285 Implements [Set](#sets), [IteratorWithIndex](#iteratorwithindex), [EnumerableWithIndex](#enumerablewithindex) 286 , [JSONSerializer](#jsonserializer) and [JSONDeserializer](#jsondeserializer) interfaces. 287 288 ```go 289 package main 290 291 import "github.com/mymmsc/gox/util/sets/treeset" 292 293 func main() { 294 set := treeset.NewWithIntComparator() // empty (keys are of type int) 295 set.Add(1) // 1 296 set.Add(2, 2, 3, 4, 5) // 1, 2, 3, 4, 5 (in order, duplicates ignored) 297 set.Remove(4) // 1, 2, 3, 5 (in order) 298 set.Remove(2, 3) // 1, 5 (in order) 299 set.Contains(1) // true 300 set.Contains(1, 5) // true 301 set.Contains(1, 6) // false 302 _ = set.Values() // []int{1,5} (in order) 303 set.Clear() // empty 304 set.Empty() // true 305 set.Size() // 0 306 } 307 ``` 308 309 #### LinkedHashSet 310 311 A [set](#sets) that preserves insertion-order. Data structure is backed by a hash table to store values 312 and [doubly-linked list](#doublylinkedlist) to store insertion ordering. 313 314 Implements [Set](#sets), [IteratorWithIndex](#iteratorwithindex), [EnumerableWithIndex](#enumerablewithindex) 315 , [JSONSerializer](#jsonserializer) and [JSONDeserializer](#jsondeserializer) interfaces. 316 317 ```go 318 package main 319 320 import "github.com/mymmsc/gox/util/sets/linkedhashset" 321 322 func main() { 323 set := linkedhashset.New() // empty 324 set.Add(5) // 5 325 set.Add(4, 4, 3, 2, 1) // 5, 4, 3, 2, 1 (in insertion-order, duplicates ignored) 326 set.Add(4) // 5, 4, 3, 2, 1 (duplicates ignored, insertion-order unchanged) 327 set.Remove(4) // 5, 3, 2, 1 (in insertion-order) 328 set.Remove(2, 3) // 5, 1 (in insertion-order) 329 set.Contains(1) // true 330 set.Contains(1, 5) // true 331 set.Contains(1, 6) // false 332 _ = set.Values() // []int{5, 1} (in insertion-order) 333 set.Clear() // empty 334 set.Empty() // true 335 set.Size() // 0 336 } 337 ``` 338 339 ### Stacks 340 341 A stack that represents a last-in-first-out (LIFO) data structure. The usual push and pop operations are provided, as 342 well as a method to peek at the top item on the stack. 343 344 Implements [Container](#containers) interface. 345 346 ```go 347 type Stack interface { 348 Push(value interface{}) 349 Pop() (value interface{}, ok bool) 350 Peek() (value interface{}, ok bool) 351 352 containers.Container 353 // Empty() bool 354 // Size() int 355 // Clear() 356 // Values() []interface{} 357 } 358 ``` 359 360 #### LinkedListStack 361 362 A [stack](#stacks) based on a [linked list](#singlylinkedlist). 363 364 Implements [Stack](#stacks), [IteratorWithIndex](#iteratorwithindex), [JSONSerializer](#jsonserializer) 365 and [JSONDeserializer](#jsondeserializer) interfaces. 366 367 ```go 368 package main 369 370 import lls "github.com/mymmsc/gox/util/stacks/linkedliststack" 371 372 func main() { 373 stack := lls.New() // empty 374 stack.Push(1) // 1 375 stack.Push(2) // 1, 2 376 stack.Values() // 2, 1 (LIFO order) 377 _, _ = stack.Peek() // 2,true 378 _, _ = stack.Pop() // 2, true 379 _, _ = stack.Pop() // 1, true 380 _, _ = stack.Pop() // nil, false (nothing to pop) 381 stack.Push(1) // 1 382 stack.Clear() // empty 383 stack.Empty() // true 384 stack.Size() // 0 385 } 386 ``` 387 388 #### ArrayStack 389 390 A [stack](#stacks) based on a [array list](#arraylist). 391 392 Implements [Stack](#stacks), [IteratorWithIndex](#iteratorwithindex), [JSONSerializer](#jsonserializer) 393 and [JSONDeserializer](#jsondeserializer) interfaces. 394 395 ```go 396 package main 397 398 import "github.com/mymmsc/gox/util/stacks/arraystack" 399 400 func main() { 401 stack := arraystack.New() // empty 402 stack.Push(1) // 1 403 stack.Push(2) // 1, 2 404 stack.Values() // 2, 1 (LIFO order) 405 _, _ = stack.Peek() // 2,true 406 _, _ = stack.Pop() // 2, true 407 _, _ = stack.Pop() // 1, true 408 _, _ = stack.Pop() // nil, false (nothing to pop) 409 stack.Push(1) // 1 410 stack.Clear() // empty 411 stack.Empty() // true 412 stack.Size() // 0 413 } 414 ``` 415 416 ### Maps 417 418 A Map is a data structure that maps keys to values. A map cannot contain duplicate keys and each key can map to at most 419 one value. 420 421 Implements [Container](#containers) interface. 422 423 ```go 424 type Map interface { 425 Put(key interface{}, value interface{}) 426 Get(key interface{}) (value interface{}, found bool) 427 Remove(key interface{}) 428 Keys() []interface{} 429 430 containers.Container 431 // Empty() bool 432 // Size() int 433 // Clear() 434 // Values() []interface{} 435 } 436 ``` 437 438 A BidiMap is an extension to the Map. A bidirectional map (BidiMap), also called a hash bag, is an associative data 439 structure in which the key-value pairs form a one-to-one relation. This relation works in both directions by allow the 440 value to also act as a key to key, e.g. a pair (a,b) thus provides a coupling between 'a' and 'b' so that 'b' can be 441 found when 'a' is used as a key and 'a' can be found when 'b' is used as a key. 442 443 ```go 444 type BidiMap interface { 445 GetKey(value interface{}) (key interface{}, found bool) 446 447 Map 448 } 449 ``` 450 451 #### HashMap 452 453 A [map](#maps) based on hash tables. Keys are unordered. 454 455 Implements [Map](#maps), [JSONSerializer](#jsonserializer) and [JSONDeserializer](#jsondeserializer) interfaces. 456 457 ```go 458 package main 459 460 import "github.com/mymmsc/gox/util/maps/hashmap" 461 462 func main() { 463 m := hashmap.New() // empty 464 m.Put(1, "x") // 1->x 465 m.Put(2, "b") // 2->b, 1->x (random order) 466 m.Put(1, "a") // 2->b, 1->a (random order) 467 _, _ = m.Get(2) // b, true 468 _, _ = m.Get(3) // nil, false 469 _ = m.Values() // []interface {}{"b", "a"} (random order) 470 _ = m.Keys() // []interface {}{1, 2} (random order) 471 m.Remove(1) // 2->b 472 m.Clear() // empty 473 m.Empty() // true 474 m.Size() // 0 475 } 476 ``` 477 478 #### TreeMap 479 480 A [map](#maps) based on [red-black tree](#redblacktree). Keys are ordered ordered with respect to 481 the [comparator](#comparator). 482 483 Implements [Map](#maps), [IteratorWithKey](#iteratorwithkey), [EnumerableWithKey](#enumerablewithkey) 484 , [JSONSerializer](#jsonserializer) and [JSONDeserializer](#jsondeserializer) interfaces. 485 486 ```go 487 package main 488 489 import "github.com/mymmsc/gox/util/maps/treemap" 490 491 func main() { 492 m := treemap.NewWithIntComparator() // empty (keys are of type int) 493 m.Put(1, "x") // 1->x 494 m.Put(2, "b") // 1->x, 2->b (in order) 495 m.Put(1, "a") // 1->a, 2->b (in order) 496 _, _ = m.Get(2) // b, true 497 _, _ = m.Get(3) // nil, false 498 _ = m.Values() // []interface {}{"a", "b"} (in order) 499 _ = m.Keys() // []interface {}{1, 2} (in order) 500 m.Remove(1) // 2->b 501 m.Clear() // empty 502 m.Empty() // true 503 m.Size() // 0 504 505 // Other: 506 m.Min() // Returns the minimum key and its value from map. 507 m.Max() // Returns the maximum key and its value from map. 508 } 509 ``` 510 511 #### LinkedHashMap 512 513 A [map](#maps) that preserves insertion-order. It is backed by a hash table to store values 514 and [doubly-linked list](doublylinkedlist) to store ordering. 515 516 Implements [Map](#maps), [IteratorWithKey](#iteratorwithkey), [EnumerableWithKey](#enumerablewithkey) 517 , [JSONSerializer](#jsonserializer) and [JSONDeserializer](#jsondeserializer) interfaces. 518 519 ```go 520 package main 521 522 import "github.com/mymmsc/gox/util/maps/linkedhashmap" 523 524 func main() { 525 m := linkedhashmap.New() // empty (keys are of type int) 526 m.Put(2, "b") // 2->b 527 m.Put(1, "x") // 2->b, 1->x (insertion-order) 528 m.Put(1, "a") // 2->b, 1->a (insertion-order) 529 _, _ = m.Get(2) // b, true 530 _, _ = m.Get(3) // nil, false 531 _ = m.Values() // []interface {}{"b", "a"} (insertion-order) 532 _ = m.Keys() // []interface {}{2, 1} (insertion-order) 533 m.Remove(1) // 2->b 534 m.Clear() // empty 535 m.Empty() // true 536 m.Size() // 0 537 } 538 539 ``` 540 541 #### HashBidiMap 542 543 A [map](#maps) based on two hashmaps. Keys are unordered. 544 545 Implements [BidiMap](#maps), [JSONSerializer](#jsonserializer) and [JSONDeserializer](#jsondeserializer) interfaces. 546 547 ```go 548 package main 549 550 import "github.com/mymmsc/gox/util/maps/hashbidimap" 551 552 func main() { 553 m := hashbidimap.New() // empty 554 m.Put(1, "x") // 1->x 555 m.Put(3, "b") // 1->x, 3->b (random order) 556 m.Put(1, "a") // 1->a, 3->b (random order) 557 m.Put(2, "b") // 1->a, 2->b (random order) 558 _, _ = m.GetKey("a") // 1, true 559 _, _ = m.Get(2) // b, true 560 _, _ = m.Get(3) // nil, false 561 _ = m.Values() // []interface {}{"a", "b"} (random order) 562 _ = m.Keys() // []interface {}{1, 2} (random order) 563 m.Remove(1) // 2->b 564 m.Clear() // empty 565 m.Empty() // true 566 m.Size() // 0 567 } 568 ``` 569 570 #### TreeBidiMap 571 572 A [map](#maps) based on red-black tree. This map guarantees that the map will be in both ascending key and value order. 573 Other than key and value ordering, the goal with this structure is to avoid duplication of elements (unlike 574 in [HashBidiMap](#hashbidimap)), which can be significant if contained elements are large. 575 576 Implements [BidiMap](#maps), [IteratorWithKey](#iteratorwithkey), [EnumerableWithKey](#enumerablewithkey) 577 , [JSONSerializer](#jsonserializer) and [JSONDeserializer](#jsondeserializer) interfaces. 578 579 ```go 580 package main 581 582 import ( 583 "github.com/mymmsc/gox/util/maps/treebidimap" 584 "github.com/mymmsc/gox/util/utils" 585 ) 586 587 func main() { 588 m := treebidimap.NewWith(utils.IntComparator, utils.StringComparator) 589 m.Put(1, "x") // 1->x 590 m.Put(3, "b") // 1->x, 3->b (ordered) 591 m.Put(1, "a") // 1->a, 3->b (ordered) 592 m.Put(2, "b") // 1->a, 2->b (ordered) 593 _, _ = m.GetKey("a") // 1, true 594 _, _ = m.Get(2) // b, true 595 _, _ = m.Get(3) // nil, false 596 _ = m.Values() // []interface {}{"a", "b"} (ordered) 597 _ = m.Keys() // []interface {}{1, 2} (ordered) 598 m.Remove(1) // 2->b 599 m.Clear() // empty 600 m.Empty() // true 601 m.Size() // 0 602 } 603 ``` 604 605 ### Trees 606 607 A tree is a widely used data data structure that simulates a hierarchical tree structure, with a root value and subtrees 608 of children, represented as a set of linked nodes; thus no cyclic links. 609 610 Implements [Container](#containers) interface. 611 612 ```go 613 type Tree interface { 614 containers.Container 615 // Empty() bool 616 // Size() int 617 // Clear() 618 // Values() []interface{} 619 } 620 ``` 621 622 #### RedBlackTree 623 624 A red–black [tree](#trees) is a binary search tree with an extra bit of data per node, its color, which can be either 625 red or black. The extra bit of storage ensures an approximately balanced tree by constraining how nodes are colored from 626 any path from the root to the leaf. Thus, it is a data structure which is a type of self-balancing binary search tree. 627 628 The balancing of the tree is not perfect but it is good enough to allow it to guarantee searching in O(log n) time, 629 where n is the total number of elements in the tree. The insertion and deletion operations, along with the tree 630 rearrangement and recoloring, are also performed in O(log n) 631 time. <sub><sup>[Wikipedia](http://en.wikipedia.org/wiki/Red%E2%80%93black_tree)</sup></sub> 632 633 Implements [Tree](#trees), [ReverseIteratorWithKey](#reverseiteratorwithkey), [JSONSerializer](#jsonserializer) 634 and [JSONDeserializer](#jsondeserializer) interfaces. 635 636 <p align="center"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/6/66/Red-black_tree_example.svg/500px-Red-black_tree_example.svg.png" width="400px" height="200px" /></p> 637 638 ```go 639 package main 640 641 import ( 642 "fmt" 643 rbt "github.com/mymmsc/gox/util/trees/redblacktree" 644 ) 645 646 func main() { 647 tree := rbt.NewWithIntComparator() // empty (keys are of type int) 648 649 tree.Put(1, "x") // 1->x 650 tree.Put(2, "b") // 1->x, 2->b (in order) 651 tree.Put(1, "a") // 1->a, 2->b (in order, replacement) 652 tree.Put(3, "c") // 1->a, 2->b, 3->c (in order) 653 tree.Put(4, "d") // 1->a, 2->b, 3->c, 4->d (in order) 654 tree.Put(5, "e") // 1->a, 2->b, 3->c, 4->d, 5->e (in order) 655 tree.Put(6, "f") // 1->a, 2->b, 3->c, 4->d, 5->e, 6->f (in order) 656 657 fmt.Println(tree) 658 // 659 // RedBlackTree 660 // │ ┌── 6 661 // │ ┌── 5 662 // │ ┌── 4 663 // │ │ └── 3 664 // └── 2 665 // └── 1 666 667 _ = tree.Values() // []interface {}{"a", "b", "c", "d", "e", "f"} (in order) 668 _ = tree.Keys() // []interface {}{1, 2, 3, 4, 5, 6} (in order) 669 670 tree.Remove(2) // 1->a, 3->c, 4->d, 5->e, 6->f (in order) 671 fmt.Println(tree) 672 // 673 // RedBlackTree 674 // │ ┌── 6 675 // │ ┌── 5 676 // └── 4 677 // │ ┌── 3 678 // └── 1 679 680 tree.Clear() // empty 681 tree.Empty() // true 682 tree.Size() // 0 683 684 // Other: 685 tree.Left() // gets the left-most (min) node 686 tree.Right() // get the right-most (max) node 687 tree.Floor(1) // get the floor node 688 tree.Ceiling(1) // get the ceiling node 689 } 690 ``` 691 692 Extending the red-black tree's functionality has been demonstrated in the 693 following [example](https://github.com/mymmsc/gox/util/blob/master/examples/redblacktreeextended/redblacktreeextended.go) 694 . 695 696 #### AVLTree 697 698 AVL [tree](#trees) is a self-balancing binary search tree. In an AVL tree, the heights of the two child subtrees of any 699 node differ by at most one; if at any time they differ by more than one, rebalancing is done to restore this property. 700 Lookup, insertion, and deletion all take O(log n) time in both the average and worst cases, where n is the number of 701 nodes in the tree prior to the operation. Insertions and deletions may require the tree to be rebalanced by one or more 702 tree rotations. 703 704 AVL trees are often compared with red–black trees because both support the same set of operations and take O(log n) time 705 for the basic operations. For lookup-intensive applications, AVL trees are faster than red–black trees because they are 706 more strictly balanced. <sub><sup>[Wikipedia](https://en.wikipedia.org/wiki/AVL_tree)</sup></sub> 707 708 Implements [Tree](#trees), [ReverseIteratorWithKey](#reverseiteratorwithkey), [JSONSerializer](#jsonserializer) 709 and [JSONDeserializer](#jsondeserializer) interfaces. 710 711 <p align="center"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/a/ad/AVL-tree-wBalance_K.svg/262px-AVL-tree-wBalance_K.svg.png" width="300px" height="180px" /><br/><sub>AVL tree with balance factors (green)</sub></p> 712 713 ```go 714 package main 715 716 import ( 717 "fmt" 718 avl "github.com/mymmsc/gox/util/trees/avltree" 719 ) 720 721 func main() { 722 tree := avl.NewWithIntComparator() // empty(keys are of type int) 723 724 tree.Put(1, "x") // 1->x 725 tree.Put(2, "b") // 1->x, 2->b (in order) 726 tree.Put(1, "a") // 1->a, 2->b (in order, replacement) 727 tree.Put(3, "c") // 1->a, 2->b, 3->c (in order) 728 tree.Put(4, "d") // 1->a, 2->b, 3->c, 4->d (in order) 729 tree.Put(5, "e") // 1->a, 2->b, 3->c, 4->d, 5->e (in order) 730 tree.Put(6, "f") // 1->a, 2->b, 3->c, 4->d, 5->e, 6->f (in order) 731 732 fmt.Println(tree) 733 // 734 // AVLTree 735 // │ ┌── 6 736 // │ ┌── 5 737 // └── 4 738 // │ ┌── 3 739 // └── 2 740 // └── 1 741 742 743 _ = tree.Values() // []interface {}{"a", "b", "c", "d", "e", "f"} (in order) 744 _ = tree.Keys() // []interface {}{1, 2, 3, 4, 5, 6} (in order) 745 746 tree.Remove(2) // 1->a, 3->c, 4->d, 5->e, 6->f (in order) 747 fmt.Println(tree) 748 // 749 // AVLTree 750 // │ ┌── 6 751 // │ ┌── 5 752 // └── 4 753 // └── 3 754 // └── 1 755 756 tree.Clear() // empty 757 tree.Empty() // true 758 tree.Size() // 0 759 } 760 ``` 761 762 #### BTree 763 764 B-tree is a self-balancing tree data structure that keeps data sorted and allows searches, sequential access, 765 insertions, and deletions in logarithmic time. The B-tree is a generalization of a binary search tree in that a node can 766 have more than two children. 767 768 According to Knuth's definition, a B-tree of order m is a tree which satisfies the following properties: 769 770 - Every node has at most m children. 771 - Every non-leaf node (except root) has at least ⌈m/2⌉ children. 772 - The root has at least two children if it is not a leaf node. 773 - A non-leaf node with k children contains k−1 keys. 774 - All leaves appear in the same level 775 776 Each internal node’s keys act as separation values which divide its subtrees. For example, if an internal node has 3 777 child nodes (or subtrees) then it must have 2 keys: a1 and a2. All values in the leftmost subtree will be less than a1, 778 all values in the middle subtree will be between a1 and a2, and all values in the rightmost subtree will be greater than 779 a2.<sub><sup>[Wikipedia](http://en.wikipedia.org/wiki/Red%E2%80%93black_tree)</sub></sup> 780 781 Implements [Tree](#trees), [ReverseIteratorWithKey](#reverseiteratorwithkey), [JSONSerializer](#jsonserializer) 782 and [JSONDeserializer](#jsondeserializer) interfaces. 783 784 <p align="center"><img src="https://upload.wikimedia.org/wikipedia/commons/thumb/6/65/B-tree.svg/831px-B-tree.svg.png" width="400px" height="111px" /></p> 785 786 ```go 787 package main 788 789 import ( 790 "fmt" 791 "github.com/mymmsc/gox/util/trees/btree" 792 ) 793 794 func main() { 795 tree := btree.NewWithIntComparator(3) // empty (keys are of type int) 796 797 tree.Put(1, "x") // 1->x 798 tree.Put(2, "b") // 1->x, 2->b (in order) 799 tree.Put(1, "a") // 1->a, 2->b (in order, replacement) 800 tree.Put(3, "c") // 1->a, 2->b, 3->c (in order) 801 tree.Put(4, "d") // 1->a, 2->b, 3->c, 4->d (in order) 802 tree.Put(5, "e") // 1->a, 2->b, 3->c, 4->d, 5->e (in order) 803 tree.Put(6, "f") // 1->a, 2->b, 3->c, 4->d, 5->e, 6->f (in order) 804 tree.Put(7, "g") // 1->a, 2->b, 3->c, 4->d, 5->e, 6->f, 7->g (in order) 805 806 fmt.Println(tree) 807 // BTree 808 // 1 809 // 2 810 // 3 811 // 4 812 // 5 813 // 6 814 // 7 815 816 _ = tree.Values() // []interface {}{"a", "b", "c", "d", "e", "f", "g"} (in order) 817 _ = tree.Keys() // []interface {}{1, 2, 3, 4, 5, 6, 7} (in order) 818 819 tree.Remove(2) // 1->a, 3->c, 4->d, 5->e, 6->f (in order) 820 fmt.Println(tree) 821 // BTree 822 // 1 823 // 3 824 // 4 825 // 5 826 // 6 827 828 tree.Clear() // empty 829 tree.Empty() // true 830 tree.Size() // 0 831 832 // Other: 833 tree.Height() // gets the height of the tree 834 tree.Left() // gets the left-most (min) node 835 tree.LeftKey() // get the left-most (min) node's key 836 tree.LeftValue() // get the left-most (min) node's value 837 tree.Right() // get the right-most (max) node 838 tree.RightKey() // get the right-most (max) node's key 839 tree.RightValue() // get the right-most (max) node's value 840 } 841 ``` 842 843 #### BinaryHeap 844 845 A binary heap is a [tree](#trees) created using a binary tree. It can be seen as a binary tree with two additional 846 constraints: 847 848 - Shape property: 849 850 A binary heap is a complete binary tree; that is, all levels of the tree, except possibly the last one (deepest) are 851 fully filled, and, if the last level of the tree is not complete, the nodes of that level are filled from left to 852 right. 853 - Heap property: 854 855 All nodes are either greater than or equal to or less than or equal to each of its children, according to a comparison 856 predicate defined for the heap. <sub><sup>[Wikipedia](http://en.wikipedia.org/wiki/Binary_heap)</sub></sup> 857 858 Implements [Tree](#trees), [ReverseIteratorWithIndex](#reverseiteratorwithindex), [JSONSerializer](#jsonserializer) 859 and [JSONDeserializer](#jsondeserializer) interfaces. 860 861 <p align="center"><img src="http://upload.wikimedia.org/wikipedia/commons/thumb/3/38/Max-Heap.svg/501px-Max-Heap.svg.png" width="300px" height="200px" /></p> 862 863 ```go 864 package main 865 866 import ( 867 "github.com/mymmsc/gox/util/trees/binaryheap" 868 "github.com/mymmsc/gox/util/utils" 869 ) 870 871 func main() { 872 873 // Min-heap 874 heap := binaryheap.NewWithIntComparator() // empty (min-heap) 875 heap.Push(2) // 2 876 heap.Push(3) // 2, 3 877 heap.Push(1) // 1, 3, 2 878 heap.Values() // 1, 3, 2 879 _, _ = heap.Peek() // 1,true 880 _, _ = heap.Pop() // 1, true 881 _, _ = heap.Pop() // 2, true 882 _, _ = heap.Pop() // 3, true 883 _, _ = heap.Pop() // nil, false (nothing to pop) 884 heap.Push(1) // 1 885 heap.Clear() // empty 886 heap.Empty() // true 887 heap.Size() // 0 888 889 // Max-heap 890 inverseIntComparator := func(a, b interface{}) int { 891 return -utils.IntComparator(a, b) 892 } 893 heap = binaryheap.NewWith(inverseIntComparator) // empty (min-heap) 894 heap.Push(2, 3, 1) // 3, 2, 1 (bulk optimized) 895 heap.Values() // 3, 2, 1 896 } 897 ``` 898 899 ## Functions 900 901 Various helper functions used throughout the library. 902 903 ### Comparator 904 905 Some data structures (e.g. TreeMap, TreeSet) require a comparator function to automatically keep their elements sorted 906 upon insertion. This comparator is necessary during the initalization. 907 908 Comparator is defined as: 909 910 Return values (int): 911 912 ```go 913 negative , if a < b 914 zero , if a == b 915 positive , if a > b 916 ``` 917 918 Comparator signature: 919 920 ```go 921 type Comparator func(a, b interface{}) int 922 ``` 923 924 All common comparators for builtin types are included in the library: 925 926 ```go 927 func StringComparator(a, b interface{}) int 928 929 func IntComparator(a, b interface{}) int 930 931 func Int8Comparator(a, b interface{}) int 932 933 func Int16Comparator(a, b interface{}) int 934 935 func Int32Comparator(a, b interface{}) int 936 937 func Int64Comparator(a, b interface{}) int 938 939 func UIntComparator(a, b interface{}) int 940 941 func UInt8Comparator(a, b interface{}) int 942 943 func UInt16Comparator(a, b interface{}) int 944 945 func UInt32Comparator(a, b interface{}) int 946 947 func UInt64Comparator(a, b interface{}) int 948 949 func Float32Comparator(a, b interface{}) int 950 951 func Float64Comparator(a, b interface{}) int 952 953 func ByteComparator(a, b interface{}) int 954 955 func RuneComparator(a, b interface{}) int 956 957 func TimeComparator(a, b interface{}) int 958 ``` 959 960 Writing custom comparators is easy: 961 962 ```go 963 package main 964 965 import ( 966 "fmt" 967 "github.com/mymmsc/gox/util/sets/treeset" 968 ) 969 970 type User struct { 971 id int 972 name string 973 } 974 975 // Custom comparator (sort by IDs) 976 func byID(a, b interface{}) int { 977 978 // Type assertion, program will panic if this is not respected 979 c1 := a.(User) 980 c2 := b.(User) 981 982 switch { 983 case c1.id > c2.id: 984 return 1 985 case c1.id < c2.id: 986 return -1 987 default: 988 return 0 989 } 990 } 991 992 func main() { 993 set := treeset.NewWith(byID) 994 995 set.Add(User{2, "Second"}) 996 set.Add(User{3, "Third"}) 997 set.Add(User{1, "First"}) 998 set.Add(User{4, "Fourth"}) 999 1000 fmt.Println(set) // {1 First}, {2 Second}, {3 Third}, {4 Fourth} 1001 } 1002 ``` 1003 1004 ### Iterator 1005 1006 All ordered containers have stateful iterators. Typically an iterator is obtained by _Iterator()_ function of an ordered 1007 container. Once obtained, iterator's _Next()_ function moves the iterator to the next element and returns true if there 1008 was a next element. If there was an element, then element's can be obtained by iterator's _Value()_ function. Depending 1009 on the ordering type, it's position can be obtained by iterator's _Index()_ or _Key()_ functions. Some containers even 1010 provide reversible iterators, essentially the same, but provide another extra _Prev()_ function that moves the iterator 1011 to the previous element and returns true if there was a previous element. 1012 1013 Note: it is unsafe to remove elements from container while iterating. 1014 1015 #### IteratorWithIndex 1016 1017 An [iterator](#iterator) whose elements are referenced by an index. 1018 1019 Typical usage: 1020 1021 ```go 1022 it := list.Iterator() 1023 for it.Next() { 1024 index, value := it.Index(), it.Value() 1025 ... 1026 } 1027 ``` 1028 1029 Other usages: 1030 1031 ```go 1032 if it.First() { 1033 firstIndex, firstValue := it.Index(), it.Value() 1034 ... 1035 } 1036 ``` 1037 1038 ```go 1039 for it.Begin(); it.Next(); { 1040 ... 1041 } 1042 ``` 1043 1044 #### IteratorWithKey 1045 1046 An [iterator](#iterator) whose elements are referenced by a key. 1047 1048 Typical usage: 1049 1050 ```go 1051 it := tree.Iterator() 1052 for it.Next() { 1053 key, value := it.Key(), it.Value() 1054 ... 1055 } 1056 ``` 1057 1058 Other usages: 1059 1060 ```go 1061 if it.First() { 1062 firstKey, firstValue := it.Key(), it.Value() 1063 ... 1064 } 1065 ``` 1066 1067 ```go 1068 for it.Begin(); it.Next(); { 1069 ... 1070 } 1071 ``` 1072 1073 #### ReverseIteratorWithIndex 1074 1075 An [iterator](#iterator) whose elements are referenced by an index. Provides all functions 1076 as [IteratorWithIndex](#iteratorwithindex), but can also be used for reverse iteration. 1077 1078 Typical usage of iteration in reverse: 1079 1080 ```go 1081 it := list.Iterator() 1082 for it.End(); it.Prev(); { 1083 index, value := it.Index(), it.Value() 1084 ... 1085 } 1086 ``` 1087 1088 Other usages: 1089 1090 ```go 1091 if it.Last() { 1092 lastIndex, lastValue := it.Index(), it.Value() 1093 ... 1094 } 1095 ``` 1096 1097 #### ReverseIteratorWithKey 1098 1099 An [iterator](#iterator) whose elements are referenced by a key. Provides all functions 1100 as [IteratorWithKey](#iteratorwithkey), but can also be used for reverse iteration. 1101 1102 Typical usage of iteration in reverse: 1103 1104 ```go 1105 it := tree.Iterator() 1106 for it.End(); it.Prev(); { 1107 key, value := it.Key(), it.Value() 1108 ... 1109 } 1110 ``` 1111 1112 Other usages: 1113 1114 ```go 1115 if it.Last() { 1116 lastKey, lastValue := it.Key(), it.Value() 1117 ... 1118 } 1119 ``` 1120 1121 ### Enumerable 1122 1123 Enumerable functions for ordered containers that implement [EnumerableWithIndex](#enumerablewithindex) 1124 or [EnumerableWithKey](#enumerablewithkey) interfaces. 1125 1126 #### EnumerableWithIndex 1127 1128 [Enumerable](#enumerable) functions for ordered containers whose values can be fetched by an index. 1129 1130 **Each** 1131 1132 Calls the given function once for each element, passing that element's index and value. 1133 1134 ```go 1135 Each(func(index int, value interface{})) 1136 ``` 1137 1138 **Map** 1139 1140 Invokes the given function once for each element and returns a container containing the values returned by the given 1141 function. 1142 1143 ```go 1144 Map(func(index int, value interface{}) interface{}) Container 1145 ``` 1146 1147 **Select** 1148 1149 Returns a new container containing all elements for which the given function returns a true value. 1150 1151 ```go 1152 Select(func(index int, value interface{}) bool) Container 1153 ``` 1154 1155 **Any** 1156 1157 Passes each element of the container to the given function and returns true if the function ever returns true for any 1158 element. 1159 1160 ```go 1161 Any(func(index int, value interface{}) bool) bool 1162 ``` 1163 1164 **All** 1165 1166 Passes each element of the container to the given function and returns true if the function returns true for all 1167 elements. 1168 1169 ```go 1170 All(func(index int, value interface{}) bool) bool 1171 ``` 1172 1173 **Find** 1174 1175 Passes each element of the container to the given function and returns the first (index,value) for which the function is 1176 true or -1,nil otherwise if no element matches the criteria. 1177 1178 ```go 1179 Find(func(index int, value interface{}) bool) (int, interface{})} 1180 ``` 1181 1182 **Example:** 1183 1184 ```go 1185 package main 1186 1187 import ( 1188 "fmt" 1189 "github.com/mymmsc/gox/util/sets/treeset" 1190 ) 1191 1192 func printSet(txt string, set *treeset.Set) { 1193 fmt.Print(txt, "[ ") 1194 set.Each(func(index int, value interface{}) { 1195 fmt.Print(value, " ") 1196 }) 1197 fmt.Println("]") 1198 } 1199 1200 func main() { 1201 set := treeset.NewWithIntComparator() 1202 set.Add(2, 3, 4, 2, 5, 6, 7, 8) 1203 printSet("Initial", set) // [ 2 3 4 5 6 7 8 ] 1204 1205 even := set.Select(func(index int, value interface{}) bool { 1206 return value.(int)%2 == 0 1207 }) 1208 printSet("Even numbers", even) // [ 2 4 6 8 ] 1209 1210 foundIndex, foundValue := set.Find(func(index int, value interface{}) bool { 1211 return value.(int)%2 == 0 && value.(int)%3 == 0 1212 }) 1213 if foundIndex != -1 { 1214 fmt.Println("Number divisible by 2 and 3 found is", foundValue, "at index", foundIndex) // value: 6, index: 4 1215 } 1216 1217 square := set.Map(func(index int, value interface{}) interface{} { 1218 return value.(int) * value.(int) 1219 }) 1220 printSet("Numbers squared", square) // [ 4 9 16 25 36 49 64 ] 1221 1222 bigger := set.Any(func(index int, value interface{}) bool { 1223 return value.(int) > 5 1224 }) 1225 fmt.Println("Set contains a number bigger than 5 is ", bigger) // true 1226 1227 positive := set.All(func(index int, value interface{}) bool { 1228 return value.(int) > 0 1229 }) 1230 fmt.Println("All numbers are positive is", positive) // true 1231 1232 evenNumbersSquared := set.Select(func(index int, value interface{}) bool { 1233 return value.(int)%2 == 0 1234 }).Map(func(index int, value interface{}) interface{} { 1235 return value.(int) * value.(int) 1236 }) 1237 printSet("Chaining", evenNumbersSquared) // [ 4 16 36 64 ] 1238 } 1239 ``` 1240 1241 #### EnumerableWithKey 1242 1243 Enumerable functions for ordered containers whose values whose elements are key/value pairs. 1244 1245 **Each** 1246 1247 Calls the given function once for each element, passing that element's key and value. 1248 1249 ```go 1250 Each(func(key interface{}, value interface{})) 1251 ``` 1252 1253 **Map** 1254 1255 Invokes the given function once for each element and returns a container containing the values returned by the given 1256 function as key/value pairs. 1257 1258 ```go 1259 Map(func(key interface{}, value interface{}) (interface{}, interface{})) Container 1260 ``` 1261 1262 **Select** 1263 1264 Returns a new container containing all elements for which the given function returns a true value. 1265 1266 ```go 1267 Select(func(key interface{}, value interface{}) bool) Container 1268 ``` 1269 1270 **Any** 1271 1272 Passes each element of the container to the given function and returns true if the function ever returns true for any 1273 element. 1274 1275 ```go 1276 Any(func(key interface{}, value interface{}) bool) bool 1277 ``` 1278 1279 **All** 1280 1281 Passes each element of the container to the given function and returns true if the function returns true for all 1282 elements. 1283 1284 ```go 1285 All(func(key interface{}, value interface{}) bool) bool 1286 ``` 1287 1288 **Find** 1289 1290 Passes each element of the container to the given function and returns the first (key,value) for which the function is 1291 true or nil,nil otherwise if no element matches the criteria. 1292 1293 ```go 1294 Find(func(key interface{}, value interface{}) bool) (interface{}, interface{}) 1295 ``` 1296 1297 **Example:** 1298 1299 ```go 1300 package main 1301 1302 import ( 1303 "fmt" 1304 "github.com/mymmsc/gox/util/maps/treemap" 1305 ) 1306 1307 func printMap(txt string, m *treemap.Map) { 1308 fmt.Print(txt, " { ") 1309 m.Each(func(key interface{}, value interface{}) { 1310 fmt.Print(key, ":", value, " ") 1311 }) 1312 fmt.Println("}") 1313 } 1314 1315 func main() { 1316 m := treemap.NewWithStringComparator() 1317 m.Put("g", 7) 1318 m.Put("f", 6) 1319 m.Put("e", 5) 1320 m.Put("d", 4) 1321 m.Put("c", 3) 1322 m.Put("b", 2) 1323 m.Put("a", 1) 1324 printMap("Initial", m) // { a:1 b:2 c:3 d:4 e:5 f:6 g:7 } 1325 1326 even := m.Select(func(key interface{}, value interface{}) bool { 1327 return value.(int) % 2 == 0 1328 }) 1329 printMap("Elements with even values", even) // { b:2 d:4 f:6 } 1330 1331 foundKey, foundValue := m.Find(func(key interface{}, value interface{}) bool { 1332 return value.(int) % 2 == 0 && value.(int) % 3 == 0 1333 }) 1334 if foundKey != nil { 1335 fmt.Println("Element with value divisible by 2 and 3 found is", foundValue, "with key", foundKey) // value: 6, index: 4 1336 } 1337 1338 square := m.Map(func(key interface{}, value interface{}) (interface{}, interface{}) { 1339 return key.(string) + key.(string), value.(int) * value.(int) 1340 }) 1341 printMap("Elements' values squared and letters duplicated", square) // { aa:1 bb:4 cc:9 dd:16 ee:25 ff:36 gg:49 } 1342 1343 bigger := m.Any(func(key interface{}, value interface{}) bool { 1344 return value.(int) > 5 1345 }) 1346 fmt.Println("Map contains element whose value is bigger than 5 is", bigger) // true 1347 1348 positive := m.All(func(key interface{}, value interface{}) bool { 1349 return value.(int) > 0 1350 }) 1351 fmt.Println("All map's elements have positive values is", positive) // true 1352 1353 evenNumbersSquared := m.Select(func(key interface{}, value interface{}) bool { 1354 return value.(int) % 2 == 0 1355 }).Map(func(key interface{}, value interface{}) (interface{}, interface{}) { 1356 return key, value.(int) * value.(int) 1357 }) 1358 printMap("Chaining", evenNumbersSquared) // { b:4 d:16 f:36 } 1359 } 1360 ``` 1361 1362 ### Serialization 1363 1364 All data structures can be serialized (marshalled) and deserialized (unmarshalled). Currently only JSON support is 1365 available. 1366 1367 #### JSONSerializer 1368 1369 Outputs the container into its JSON representation. 1370 1371 Typical usage for key-value structures: 1372 1373 ```go 1374 package main 1375 1376 import ( 1377 "fmt" 1378 "github.com/mymmsc/gox/util/maps/hashmap" 1379 ) 1380 1381 func main() { 1382 m := hashmap.New() 1383 m.Put("a", "1") 1384 m.Put("b", "2") 1385 m.Put("c", "3") 1386 1387 json, err := m.ToJSON() 1388 if err != nil { 1389 fmt.Println(err) 1390 } 1391 fmt.Println(string(json)) // {"a":"1","b":"2","c":"3"} 1392 ``` 1393 1394 Typical usage for value-only structures: 1395 1396 ```go 1397 package main 1398 1399 import ( 1400 "fmt" 1401 "github.com/mymmsc/gox/util/lists/arraylist" 1402 ) 1403 1404 func main() { 1405 list := arraylist.New() 1406 list.Add("a", "b", "c") 1407 1408 json, err := list.ToJSON() 1409 if err != nil { 1410 fmt.Println(err) 1411 } 1412 fmt.Println(string(json)) // ["a","b","c"] 1413 } 1414 ``` 1415 1416 #### JSONDeserializer 1417 1418 Populates the container with elements from the input JSON representation. 1419 1420 Typical usage for key-value structures: 1421 1422 ```go 1423 package main 1424 1425 import ( 1426 "fmt" 1427 "github.com/mymmsc/gox/util/maps/hashmap" 1428 ) 1429 1430 func main() { 1431 hm := hashmap.New() 1432 1433 json := []byte(`{"a":"1","b":"2"}`) 1434 err := hm.FromJSON(json) 1435 if err != nil { 1436 fmt.Println(err) 1437 } 1438 fmt.Println(hm) // HashMap map[b:2 a:1] 1439 } 1440 ``` 1441 1442 Typical usage for value-only structures: 1443 1444 ```go 1445 package main 1446 1447 import ( 1448 "fmt" 1449 "github.com/mymmsc/gox/util/lists/arraylist" 1450 ) 1451 1452 func main() { 1453 list := arraylist.New() 1454 1455 json := []byte(`["a","b"]`) 1456 err := list.FromJSON(json) 1457 if err != nil { 1458 fmt.Println(err) 1459 } 1460 fmt.Println(list) // ArrayList ["a","b"] 1461 } 1462 ``` 1463 1464 ### Sort 1465 1466 Sort is a general purpose sort function. 1467 1468 Lists have an in-place _Sort()_ function and all containers can return their sorted elements via _ 1469 containers.GetSortedValues()_ function. 1470 1471 Internally these all use the _utils.Sort()_ method: 1472 1473 ```go 1474 package main 1475 1476 import "github.com/mymmsc/gox/util/utils" 1477 1478 func main() { 1479 strings := []interface{}{} // [] 1480 strings = append(strings, "d") // ["d"] 1481 strings = append(strings, "a") // ["d","a"] 1482 strings = append(strings, "b") // ["d","a",b" 1483 strings = append(strings, "c") // ["d","a",b","c"] 1484 utils.Sort(strings, utils.StringComparator) // ["a","b","c","d"] 1485 } 1486 ``` 1487 1488 ### Container 1489 1490 Container specific operations: 1491 1492 ```go 1493 // Returns sorted container''s elements with respect to the passed comparator. 1494 // Does not effect the ordering of elements within the container. 1495 func GetSortedValues(container Container, comparator utils.Comparator) []interface{} 1496 ``` 1497 1498 Usage: 1499 1500 ```go 1501 package main 1502 1503 import ( 1504 "github.com/mymmsc/gox/util/lists/arraylist" 1505 "github.com/mymmsc/gox/util/utils" 1506 ) 1507 1508 func main() { 1509 list := arraylist.New() 1510 list.Add(2, 1, 3) 1511 values := GetSortedValues(container, utils.StringComparator) // [1, 2, 3] 1512 } 1513 ``` 1514 1515 ## Appendix 1516 1517 ### Motivation 1518 1519 Collections and data structures found in other languages: Java Collections, C++ Standard Template Library (STL) 1520 containers, Qt Containers, Ruby Enumerable etc. 1521 1522 ### Goals 1523 1524 **Fast algorithms**: 1525 1526 - Based on decades of knowledge and experiences of other libraries mentioned above. 1527 1528 **Memory efficient algorithms**: 1529 1530 - Avoiding to consume memory by using optimal algorithms and data structures for the given set of problems, e.g. 1531 red-black tree in case of TreeMap to avoid keeping redundant sorted array of keys in memory. 1532 1533 **Easy to use library**: 1534 1535 - Well-structured library with minimalistic set of atomic operations from which more complex operations can be crafted. 1536 1537 **Stable library**: 1538 1539 - Only additions are permitted keeping the library backward compatible. 1540 1541 **Solid documentation and examples**: 1542 1543 - Learning by example. 1544 1545 **Production ready**: 1546 1547 - Used in production. 1548 1549 **No dependencies**: 1550 1551 - No external imports. 1552 1553 There is often a tug of war between speed and memory when crafting algorithms. We choose to optimize for speed in most 1554 cases within reasonable limits on memory consumption. 1555 1556 Thread safety is not a concern of this project, this should be handled at a higher level. 1557 1558 ### Testing and Benchmarking 1559 1560 This takes a while, so test within sub-packages: 1561 1562 `go test -run=NO_TEST -bench . -benchmem -benchtime 1s ./...` 1563 1564 <p align="center"><img src="https://cloud.githubusercontent.com/assets/3115942/16892979/5e698d46-4b27-11e6-864b-cb2b865327b6.png" /></p> 1565 1566 ### Contributing 1567 1568 Biggest contribution towards this library is to use it and give us feedback for further improvements and additions. 1569 1570 For direct contributions, _pull request_ into master branch or ask to become a contributor. 1571 1572 Coding style: 1573 1574 ```shell 1575 # Install tooling and set path: 1576 go get github.com/golang/lint/golint 1577 go get github.com/fzipp/gocyclo 1578 go get github.com/kisielk/errcheck 1579 export PATH=$PATH:$GOPATH/bin 1580 1581 # Fix errors and warnings: 1582 go fmt ./... && gofmt -s -w . && go vet ./... && go get ./... && go test ./... && golint ./... && gocyclo -avg -over 15 . && errcheck ./... 1583 ``` 1584 1585 ### License 1586 1587 This library is distributed under the BSD-style license found in 1588 the [LICENSE](https://github.com/mymmsc/gox/util/blob/master/LICENSE) file. 1589 1590 ### Sponsors 1591 1592 ## <a href="https://www.browserstack.com/?ref=gods"><img src="http://www.hajdarevic.net/browserstack.svg" alt="BrowserStack" width="250"/></a> 1593 1594 [BrowserStack](https://www.browserstack.com/?ref=webhook) is a cloud-based cross-browser testing tool that enables 1595 developers to test their websites across various browsers on different operating systems and mobile devices, without 1596 requiring users to install virtual machines, devices or emulators.