A set is a data structure that can store elements and no repeated values. It is a computer implementation of the mathematical concept of a finite set. Unlike most other collection types, rather than retrieving a specific element from a set, one typically tests an element for membership in a set. This structed is often used to ensure that no duplicates are present in a collection.
All sets implement the set interface with the following methods:
```go
type Interface interface {
Add(elements ...interface{})
Remove(elements ...interface{})
Contains(elements ...interface{}) bool
containers.Interface
// Empty() bool
// Size() int
// Clear()
// Values() []interface{}
}
```
#####HashSet
This structure implements the Set interface and is backed by a hash table (actually a Go's map). It makes no guarantees as to the iteration order of the set, since Go randomizes this iteration order on maps.
This structure offers constant time performance for the basic operations (add, remove, contains and size).
This structure implements the Set interface and is backed by a red-black tree to keep the elements sorted with respect to the comparator.
This implementation provides guaranteed log(n) time cost for the basic operations (add, remove and contains).
```go
package main
import "github.com/emirpasic/gods/sets/treeset"
Containers are either ordered or unordered. All ordered containers provide [stateful iterators](#iterator) and some of them allow [enumerable functions](#enumerable).
func main() {
set := treeset.NewWithIntComparator() // empty (keys are of type int)
| [BinaryHeap](#binaryheap) | yes | yes | no | index |
####Lists
### Lists
A list is a data structure that can store values and may have repeated values. There is no ordering in a list. The user can access and remove a value by the index position.
A list is a data structure that stores values and may have repeated values.
All lists implement the list interface with the following methods:
Implements [Container](#containers) interface.
```go
type Interface interface {
type List interface {
Get(index int) (interface{}, bool)
Remove(index int)
Add(values ...interface{})
@ -140,7 +81,7 @@ type Interface interface {
Swap(index1, index2 int)
Insert(index int, values ...interface{})
containers.Interface
containers.Container
// Empty() bool
// Size() int
// Clear()
@ -148,12 +89,11 @@ type Interface interface {
}
```
#####ArrayList
This structure implements the List interface and is backed by a dynamic array that grows and shrinks implicitly (by 100% when capacity is reached).
#### ArrayList
Direct access method _Get(index)_ is guaranteed a constant time performance. Remove is of linear time performance. Checking with _Contains()_ is of quadratic complexity.
A [list](#lists) backed by a dynamic array that grows and shrinks implicitly.
Implements [List](#lists), [IteratorWithIndex](#iteratorwithindex) and [EnumerableWithIndex](#enumerablewithindex) interfaces.
```go
package main
@ -186,11 +126,11 @@ func main() {
}
```
#####SinglyLinkedList
####SinglyLinkedList
This structure implements the _List_ interface and is a linked data structure where each value points to the next in the list.
A [list](#lists) where each element points to the next element in the list.
Direct access method _Get(index)_ and _Remove()_ are of linear performance. _Append_ and _Prepend_ are of constant time performance. Checking with _Contains()_ is of quadratic complexity.
Implements [List](#lists), [IteratorWithIndex](#iteratorwithindex) and [EnumerableWithIndex](#enumerablewithindex) interfaces.
```go
package main
@ -223,11 +163,11 @@ func main() {
}
```
#####DoublyLinkedList
####DoublyLinkedList
This structure implements the _List_ interface and is a linked data structure where each value points to the next and previous element in the list.
A [list](#lists) where each element points to the next and previous elements in the list.
Direct access method _Get(index)_ and _Remove()_ are of linear performance. _Append_ and _Prepend_ are of constant time performance. Checking with _Contains()_ is of quadratic complexity.
Implements [List](#lists), [IteratorWithIndex](#iteratorwithindex) and [EnumerableWithIndex](#enumerablewithindex) interfaces.
```go
package main
@ -260,19 +200,93 @@ func main() {
}
```
### Sets
####Stacks
A set is a data structure that can store elements and has no repeated values. It is a computer implementation of the mathematical concept of a finite set. Unlike most other collection types, rather than retrieving a specific element from a set, one typically tests an element for membership in a set. This structed is often used to ensure that no duplicates are present in a container.
The stack interface represents a last-in-first-out (LIFO) collection of objects. The usual push and pop operations are provided, as well as a method to peek at the top item on the stack, a method to check whether the stack is empty and the size (number of elements).
Implements [Container](#containers) interface.
All stacks implement the stack interface with the following methods:
```go
type Interface interface {
type Set interface {
Add(elements ...interface{})
Remove(elements ...interface{})
Contains(elements ...interface{}) bool
containers.Container
// Empty() bool
// Size() int
// Clear()
// Values() []interface{}
}
```
#### HashSet
A [set](#sets) backed by a hash table (actually a Go's map). It makes no guarantees as to the iteration order of the set.
A stack that represents a last-in-first-out (LIFO) data structure. The usual push and pop operations are provided, as well as a method to peek at the top item on the stack.
Implements [Container](#containers) interface.
```go
type Stack interface {
Push(value interface{})
Pop() (value interface{}, ok bool)
Peek() (value interface{}, ok bool)
containers.Interface
containers.Container
// Empty() bool
// Size() int
// Clear()
@ -280,11 +294,11 @@ type Interface interface {
}
```
#####LinkedListStack
####LinkedListStack
This stack structure is based on a linked list, i.e. each previous element has a point to the next.
A [stack](#stacks) based on a [linked list](#singlylinkedlist).
All operations are guaranteed constant time performance, except _Values()_, which is as always of linear time performance.
Implements [Stack](#stacks) and [IteratorWithIndex](#iteratorwithindex) interfaces.
```go
package main
@ -307,11 +321,11 @@ func main() {
}
```
#####ArrayStack
####ArrayStack
This stack structure is back by ArrayList.
A [stack](#stacks) based on a [array list](#arraylist).
All operations are guaranted constant time performance.
Implements [Stack](#stacks) and [IteratorWithIndex](#iteratorwithindex) interfaces.
```go
package main
@ -334,19 +348,20 @@ func main() {
}
```
####Maps
### Maps
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 one value.
Structure that maps keys to values. A map cannot contain duplicate keys and each key can map to at most one value.
Implements [Container](#containers) interface.
All maps implement the map interface with the following methods:
```go
type Interface interface {
type Map interface {
Put(key interface{}, value interface{})
Get(key interface{}) (value interface{}, found bool)
Remove(key interface{})
Keys() []interface{}
containers.Interface
containers.Container
// Empty() bool
// Size() int
// Clear()
@ -354,11 +369,11 @@ type Interface interface {
}
```
#####HashMap
####HashMap
Map structure based on hash tables, more exactly, Go's map. Keys are unordered.
A [map](#maps) based on hash tables. Keys are unordered.
All operations are guaranted constant time performance, except _Key()_ and _Values()_ retrieval that of linear time performance.
Map structure based on our red-black tree implementation. Keys are ordered with respect to the passed comparator.
A [map](#maps) based on [red-black tree](#redblacktree). Keys are ordered ordered with respect to the [comparator](#comparator).
_Put()_, _Get()_ and _Remove()_ are guaranteed log(n) time performance.
_Key()_ and _Values()_ methods return keys and values respectively in order of the keys. These meethods are quaranteed linear time performance.
Implements [Map](#maps), [IteratorWithKey](#iteratorwithkey) and [EnumerableWithKey](#enumerablewithkey) interfaces.
```go
package main
@ -414,14 +427,15 @@ func main() {
}
```
####Trees
###Trees
A tree is a widely used data data structure that simulates a hierarchical tree structure, with a root value and subtrees of children, represented as a set of linked nodes; thus no cyclic links.
All trees implement the tree interface with the following methods:
Implements [Container](#containers) interface.
```go
type Interface interface {
containers.Interface
type Tree interface {
containers.Container
// Empty() bool
// Size() int
// Clear()
@ -429,11 +443,13 @@ type Interface interface {
}
```
#####RedBlackTree
####RedBlackTree
A red–black tree is a binary search tree with an extra bit of data per node, its color, which can be either red or black. The extra bit of storage ensures an approximately balanced tree by constraining how nodes are colored from any path from the root to the leaf. Thus, it is a data structure which is a type of self-balancing binary search tree.
A red–black [tree](#trees) is a binary search tree with an extra bit of data per node, its color, which can be either red or black. The extra bit of storage ensures an approximately balanced tree by constraining how nodes are colored from any path from the root to the leaf. Thus, it is a data structure which is a type of self-balancing binary search tree.
The balancing of the tree is not perfect but it is good enough to allow it to guarantee searching in O(log n) time, where n is the total number of elements in the tree. The insertion and deletion operations, along with the tree rearrangement and recoloring, are also performed in O(log n) time.<small>[Wikipedia](http://en.wikipedia.org/wiki/Red%E2%80%93black_tree)</small>
The balancing of the tree is not perfect but it is good enough to allow it to guarantee searching in O(log n) time, where n is the total number of elements in the tree. The insertion and deletion operations, along with the tree rearrangement and recoloring, are also performed in O(log n) time. <small>[Wikipedia](http://en.wikipedia.org/wiki/Red%E2%80%93black_tree)</small>
Implements [Tree](#trees) and [IteratorWithKey](#iteratorwithkey) interfaces.
tree := rbt.NewWithIntComparator() // empty(keys are of type int)
tree := rbt.NewWithIntComparator() // empty(keys are of type int)
tree.Put(1, "x") // 1->x
tree.Put(2, "b") // 1->x, 2->b (in order)
@ -493,9 +509,9 @@ func main() {
Extending the red-black tree's functionality has been demonstrated in the following [example](https://github.com/emirpasic/gods/blob/master/examples/redblacktreeextended.go).
#####BinaryHeap
####BinaryHeap
A binary heap is a heap data structure created using a binary tree. It can be seen as a binary tree with two additional constraints:
A binary heap is a [tree](#trees) created using a binary tree. It can be seen as a binary tree with two additional constraints:
- Shape property:
@ -504,6 +520,8 @@ A binary heap is a heap data structure created using a binary tree. It can be se
All nodes are either greater than or equal to or less than or equal to each of its children, according to a comparison predicate defined for the heap. <small>[Wikipedia](http://en.wikipedia.org/wiki/Binary_heap)</small>
Implements [Tree](#trees) and [IteratorWithIndex](#iteratorwithindex) interfaces.
Various helper functions used throughout the library.
#### Comparator
### Comparator
Some data structures (e.g. TreeMap, TreeSet) require a comparator function to sort their contained elements. This comparator is necessary during the initalization.
Some data structures (e.g. TreeMap, TreeSet) require a comparator function to automatically keep their elements sorted upon insertion. This comparator is necessary during the initalization.
Comparator is defined as:
```go
Return values:
-1, if a <b
0, if a == b
1, if a > b
```go
-1, if a <b
0, if a == b
1, if a > b
```
Comparator signature:
type Comparator func(a, b interface{}) int
```go
type Comparator func(a, b interface{}) int
```
Two common comparators are included in the library:
#####IntComparator
```go
func IntComparator(a, b interface{}) int {
aInt := a.(int)
bInt := b.(int)
switch {
case aInt > bInt:
return 1
case aInt <bInt:
return -1
default:
return 0
}
}
func IntComparator(a, b interface{}) int
```
#####StringComparator
```go
func StringComparator(a, b interface{}) int {
s1 := a.(string)
s2 := b.(string)
min := len(s2)
if len(s1) <len(s2){
min = len(s1)
}
diff := 0
for i := 0; i <min&&diff ==0;i++{
diff = int(s1[i]) - int(s2[i])
}
if diff == 0 {
diff = len(s1) - len(s2)
}
if diff <0{
return -1
}
if diff > 0 {
return 1
}
return 0
}
func StringComparator(a, b interface{}) int
```
#####CustomComparator
Writing custom comparators is easy:
```go
package main
@ -625,7 +611,7 @@ type User struct {
name string
}
// Comparator function (sort by IDs)
// Custom comparator (sort by IDs)
func byID(a, b interface{}) int {
// Type assertion, program will panic if this is not respected
@ -654,7 +640,267 @@ func main() {
}
```
#### Sort
### Iterator
All ordered containers have stateful iterators. Typically an iterator is obtained by _Iterator()_ function of an ordered container. Once obtained, iterator's _Next()_ function moves the iterator to the next element and returns true if there was a next element. If there was an element, then element's can be obtained by iterator's _Value()_ function. Depending on the ordering type, it's position can be obtained by iterator's _Index()_ or _Key()_ functions.
#### IteratorWithIndex
A [iterator](#iterator) whose elements are referenced by an index. Typical usage:
```go
it := list.Iterator()
for it.Next() {
index, value := it.Index(), it.Value()
...
}
```
#### IteratorWithKey
A [iterator](#iterator) whose elements are referenced by a key. Typical usage:
```go
it := map.Iterator()
for it.Next() {
key, value := it.Key(), it.Value()
...
}
```
### Enumerable
Enumerable functions for ordered containers that implement [EnumerableWithIndex](#enumerablewithindex) or [EnumerableWithKey](#enumerablewithkey) interfaces.
#### EnumerableWithIndex
[Enumerable](#enumerable) functions for ordered containers whose values can be fetched by an index.
**Each**
Calls the given function once for each element, passing that element's index and value.
```go
Each(func(index int, value interface{}))
```
**Map**
Invokes the given function once for each element and returns a container containing the values returned by the given function.
```go
Map(func(index int, value interface{}) interface{}) Container
```
**Select**
Returns a new container containing all elements for which the given function returns a true value.
```go
Select(func(index int, value interface{}) bool) Container
```
**Any**
Passes each element of the container to the given function and returns true if the function ever returns true for any element.
```go
Any(func(index int, value interface{}) bool) bool
```
**All**
Passes each element of the container to the given function and returns true if the function returns true for all elements.
```go
All(func(index int, value interface{}) bool) bool
```
**Find**
Passes each element of the container to the given function and returns the first (index,value) for which the function is true or -1,nil otherwise if no element matches the criteria.
```go
Find(func(index int, value interface{}) bool) (int, interface{})}
```
**Example:**
```go
package main
import (
"fmt"
"github.com/emirpasic/gods/sets/treeset"
)
func printSet(txt string, set *treeset.Set) {
fmt.Print(txt, "[ ")
set.Each(func(index int, value interface{}) {
fmt.Print(value, " ")
})
fmt.Println("]")
}
func main() {
set := treeset.NewWithIntComparator()
set.Add(2, 3, 4, 2, 5, 6, 7, 8)
printSet("Initial", set) // [ 2 3 4 5 6 7 8 ]
even := set.Select(func(index int, value interface{}) bool {
return value.(int)%2 == 0
})
printSet("Even numbers", even) // [ 2 4 6 8 ]
foundIndex, foundValue := set.Find(func(index int, value interface{}) bool {
return value.(int)%2 == 0 && value.(int)%3 == 0
})
if foundIndex != -1 {
fmt.Println("Number divisible by 2 and 3 found is", foundValue, "at index", foundIndex) // value: 6, index: 4
}
square := set.Map(func(index int, value interface{}) interface{} {
Enumerable functions for ordered containers whose values whose elements are key/value pairs.
**Each**
Calls the given function once for each element, passing that element's key and value.
```go
Each(func(key interface{}, value interface{}))
```
**Map**
Invokes the given function once for each element and returns a container containing the values returned by the given function as key/value pairs.
```go
Map(func(key interface{}, value interface{}) (interface{}, interface{})) Container
```
**Select**
Returns a new container containing all elements for which the given function returns a true value.
```go
Select(func(key interface{}, value interface{}) bool) Container
```
**Any**
Passes each element of the container to the given function and returns true if the function ever returns true for any element.
```go
Any(func(key interface{}, value interface{}) bool) bool
```
**All**
Passes each element of the container to the given function and returns true if the function returns true for all elements.
```go
All(func(key interface{}, value interface{}) bool) bool
```
**Find**
Passes each element of the container to the given function and returns the first (key,value) for which the function is true or nil,nil otherwise if no element matches the criteria.
```go
Find(func(key interface{}, value interface{}) bool) (interface{}, interface{})
Sort uses timsort for best performance on real-world data. Lists have an in-place _Sort()_ method. All containers can return their sorted elements via _GetSortedValues()_ call.
@ -675,11 +921,41 @@ func main() {
}
```
## Motivations
### Container
Container specific operations:
```go
// Returns sorted container''s elements with respect to the passed comparator.
// Does not effect the ordering of elements within the container.
Collections and data structures found in other languages: Java Collections, C++ Standard Template Library (STL) containers, Qt Containers, etc.
Collections and data structures found in other languages: Java Collections, C++ Standard Template Library (STL) containers, Qt Containers, Ruby Enumerable etc.
## Goals
### Goals
**Fast algorithms**:
@ -709,17 +985,17 @@ There is often a tug of war between speed and memory when crafting algorithms. W
Thread safety is not a concern of this project, this should be handled at a higher level.
## Testing and Benchmarking
### Testing and Benchmarking
`go test -v -bench . -benchmem -benchtime 1s ./...`
## Contributing
### Contributing
Biggest contribution towards this library is to use it and give us feedback for further improvements and additions.
For direct contributions, branch of from master and do _pull request_.
For direct contributions, _pull request_ into master or ask to become a contributor.
## License
### License
This library is distributed under the BSD-style license found in the [LICENSE](https://github.com/emirpasic/gods/blob/master/LICENSE) file.