diff --git a/README.md b/README.md index deed77b..bc130be 100644 --- a/README.md +++ b/README.md @@ -1,19 +1,19 @@ -[![Build Status](https://travis-ci.org/emirpasic/gods.svg)](https://travis-ci.org/emirpasic/gods) [![GoDoc](https://godoc.org/github.com/emirpasic/gods?status.svg)](https://godoc.org/github.com/emirpasic/gods) +[![GoDoc](https://godoc.org/github.com/emirpasic/gods?status.svg)](https://godoc.org/github.com/emirpasic/gods) [![Build Status](https://travis-ci.org/emirpasic/gods.svg)](https://travis-ci.org/emirpasic/gods) [![PyPI](https://img.shields.io/pypi/l/Django.svg?maxAge=2592000)](https://github.com/emirpasic/gods/blob/enums/LICENSE) # GoDS (Go Data Structures) -Implementation of various data structures in Go. +Implementation of various data structures and algorithms in Go. ## Data Structures - [Containers](#containers) - - [Sets](#sets) - - [HashSet](#hashset) - - [TreeSet](#treeset) - [Lists](#lists) - [ArrayList](#arraylist) - [SinglyLinkedList](#singlylinkedlist) - [DoublyLinkedList](#doublylinkedlist) + - [Sets](#sets) + - [HashSet](#hashset) + - [TreeSet](#treeset) - [Stacks](#stacks) - [LinkedListStack](#linkedliststack) - [ArrayStack](#arraystack) @@ -25,15 +25,23 @@ Implementation of various data structures in Go. - [BinaryHeap](#binaryheap) - [Functions](#functions) - [Comparator](#comparator) + - [Iterator](#iterator) + - [IteratorWithIndex](#iteratorwithindex) + - [IteratorWithKey](#iteratorwithkey) + - [Enumerable](#enumerable) + - [EnumerableWithIndex](#enumerablewithindex) + - [EnumerableWithKey](#enumerablewithkey) - [Sort](#sort) - + - [Container](#container) +- [Appendix](#appendix) + -###Containers +## Containers All data structures implement the container interface with the following methods: ```go -type Interface interface { +type Container interface { Empty() bool Size() int Clear() @@ -41,97 +49,30 @@ type Interface interface { } ``` -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. -// Uses timsort. -func GetSortedValues(container Interface, comparator utils.Comparator) []interface{} { -``` - -####Sets - -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). - -```go -package main - -import "github.com/emirpasic/gods/sets/hashset" - -func main() { - set := hashset.New() // empty - set.Add(1) // 1 - set.Add(2, 2, 3, 4, 5) // 3, 1, 2, 4, 5 (random order, duplicates ignored) - set.Remove(4) // 5, 3, 2, 1 (random order) - set.Remove(2, 3) // 1, 5 (random order) - set.Contains(1) // true - set.Contains(1, 5) // true - set.Contains(1, 6) // false - _ = set.Values() // []int{5,1} (random order) - set.Clear() // empty - set.Empty() // true - set.Size() // 0 -} -``` - -#####TreeSet - -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) - set.Add(1) // 1 - set.Add(2, 2, 3, 4, 5) // 1, 2, 3, 4, 5 (in order, duplicates ignored) - set.Remove(4) // 1, 2, 3, 5 (in order) - set.Remove(2, 3) // 1, 5 (in order) - set.Contains(1) // true - set.Contains(1, 5) // true - set.Contains(1, 6) // false - _ = set.Values() // []int{1,5} (in order) - set.Clear() // empty - set.Empty() // true - set.Size() // 0 -} -``` +| Container | Ordered | [Iterator](#iterator) | [Enumerable](#enumerable) | Ordered by | +| :--- | :---: | :---: | :---: | :---: | +| [ArrayList](#arraylist) | yes | yes | yes | index | +| [SinglyLinkedList](#singlylinkedlist) | yes | yes | yes | index | +| [DoublyLinkedList](#doublylinkedlist) | yes | yes | yes | index | +| [HashSet](#hashset) | no | no | no | index | +| [TreeSet](#treeset) | yes | yes | yes | index | +| [LinkedListStack](#linkedliststack) | yes | yes | no | index | +| [ArrayStack](#arraystack) | yes | yes | no | index | +| [HashMap](#hashmap) | no | no | no | key | +| [TreeMap](#treemap) | yes | yes | yes | key | +| [RedBlackTree](#redblacktree) | yes | yes | no | key | +| [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. + +Implements [Set](#sets) interface. + +```go +package main + +import "github.com/emirpasic/gods/sets/hashset" + +func main() { + set := hashset.New() // empty + set.Add(1) // 1 + set.Add(2, 2, 3, 4, 5) // 3, 1, 2, 4, 5 (random order, duplicates ignored) + set.Remove(4) // 5, 3, 2, 1 (random order) + set.Remove(2, 3) // 1, 5 (random order) + set.Contains(1) // true + set.Contains(1, 5) // true + set.Contains(1, 6) // false + _ = set.Values() // []int{5,1} (random order) + set.Clear() // empty + set.Empty() // true + set.Size() // 0 +} +``` + +#### TreeSet + +A [set](#sets) backed by a [red-black tree](#redblacktree) to keep the elements ordered with respect to the [comparator](#comparator). + +Implements [Set](#sets), [IteratorWithIndex](#iteratorwithindex) and [EnumerableWithIndex](#enumerablewithindex) interfaces. + +```go +package main + +import "github.com/emirpasic/gods/sets/treeset" + +func main() { + set := treeset.NewWithIntComparator() // empty (keys are of type int) + set.Add(1) // 1 + set.Add(2, 2, 3, 4, 5) // 1, 2, 3, 4, 5 (in order, duplicates ignored) + set.Remove(4) // 1, 2, 3, 5 (in order) + set.Remove(2, 3) // 1, 5 (in order) + set.Contains(1) // true + set.Contains(1, 5) // true + set.Contains(1, 6) // false + _ = set.Values() // []int{1,5} (in order) + set.Clear() // empty + set.Empty() // true + set.Size() // 0 +} +``` + +### Stacks + +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. +Implements [Map](#maps) interface. ```go package main @@ -368,7 +383,7 @@ import "github.com/emirpasic/gods/maps/hashmap" func main() { m := hashmap.New() // empty m.Put(1, "x") // 1->x - m.Put(2, "b") // 2->b, 1->x (random order) + m.Put(2, "b") // 2->b, 1->x (random order) m.Put(1, "a") // 2->b, 1->a (random order) _, _ = m.Get(2) // b, true _, _ = m.Get(3) // nil, false @@ -381,13 +396,11 @@ func main() { } ``` -#####TreeMap +#### TreeMap -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.[Wikipedia](http://en.wikipedia.org/wiki/Red%E2%80%93black_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. [Wikipedia](http://en.wikipedia.org/wiki/Red%E2%80%93black_tree) + +Implements [Tree](#trees) and [IteratorWithKey](#iteratorwithkey) interfaces.
@@ -446,7 +462,7 @@ import ( ) func main() { - 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. [Wikipedia](http://en.wikipedia.org/wiki/Binary_heap) +Implements [Tree](#trees) and [IteratorWithIndex](#iteratorwithindex) interfaces. +
```go @@ -544,74 +562,42 @@ func main() { } ``` -### Functions +## Functions 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{} { + return value.(int) * value.(int) + }) + printSet("Numbers squared", square) // [ 4 9 16 25 36 49 64 ] + + bigger := set.Any(func(index int, value interface{}) bool { + return value.(int) > 5 + }) + fmt.Println("Set contains a number bigger than 5 is ", bigger) // true + + positive := set.All(func(index int, value interface{}) bool { + return value.(int) > 0 + }) + fmt.Println("All numbers are positive is", positive) // true + + evenNumbersSquared := set.Select(func(index int, value interface{}) bool { + return value.(int)%2 == 0 + }).Map(func(index int, value interface{}) interface{} { + return value.(int) * value.(int) + }) + printSet("Chaining", evenNumbersSquared) // [ 4 16 36 64 ] +} +``` + +#### EnumerableWithKey + +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{}) +``` + +**Example:** + +```go +package main + +import ( + "fmt" + "github.com/emirpasic/gods/maps/treemap" +) + +func printMap(txt string, m *treemap.Map) { + fmt.Print(txt, " { ") + m.Each(func(key interface{}, value interface{}) { + fmt.Print(key, ":", value, " ") + }) + fmt.Println("}") +} + +func main() { + m := treemap.NewWithStringComparator() + m.Put("g", 7) + m.Put("f", 6) + m.Put("e", 5) + m.Put("d", 4) + m.Put("c", 3) + m.Put("b", 2) + m.Put("a", 1) + printMap("Initial", m) // { a:1 b:2 c:3 d:4 e:5 f:6 g:7 } + + even := m.Select(func(key interface{}, value interface{}) bool { + return value.(int) % 2 == 0 + }) + printMap("Elements with even values", even) // { b:2 d:4 f:6 } + + foundKey, foundValue := m.Find(func(key interface{}, value interface{}) bool { + return value.(int) % 2 == 0 && value.(int) % 3 == 0 + }) + if foundKey != nil { + fmt.Println("Element with value divisible by 2 and 3 found is", foundValue, "with key", foundKey) // value: 6, index: 4 + } + + square := m.Map(func(key interface{}, value interface{}) (interface{}, interface{}) { + return key.(string) + key.(string), value.(int) * value.(int) + }) + printMap("Elements' values squared and letters duplicated", square) // { aa:1 bb:4 cc:9 dd:16 ee:25 ff:36 gg:49 } + + bigger := m.Any(func(key interface{}, value interface{}) bool { + return value.(int) > 5 + }) + fmt.Println("Map contains element whose value is bigger than 5 is", bigger) // true + + positive := m.All(func(key interface{}, value interface{}) bool { + return value.(int) > 0 + }) + fmt.Println("All map's elements have positive values is", positive) // true + + evenNumbersSquared := m.Select(func(key interface{}, value interface{}) bool { + return value.(int) % 2 == 0 + }).Map(func(key interface{}, value interface{}) (interface{}, interface{}) { + return key, value.(int) * value.(int) + }) + printMap("Chaining", evenNumbersSquared) // { b:4 d:16 f:36 } +} +``` + +### Sort 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. +// Uses timsort. +func GetSortedValues(container Container, comparator utils.Comparator) []interface{} +``` + +Usage: + +```go +package main + +import ( + "github.com/emirpasic/gods/lists/arraylist" + "github.com/emirpasic/gods/utils" +) + +func main() { + list := arraylist.New() + list.Add(2, 1, 3) + values := GetSortedValues(container, utils.StringComparator) // [1, 2, 3] +} +``` + +## Appendix + +### Motivation -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. diff --git a/containers/containers.go b/containers/containers.go index 48e9b15..2da6c26 100644 --- a/containers/containers.go +++ b/containers/containers.go @@ -30,7 +30,7 @@ package containers import "github.com/emirpasic/gods/utils" -type Interface interface { +type Container interface { Empty() bool Size() int Clear() @@ -40,7 +40,7 @@ type Interface interface { // Returns sorted container's elements with respect to the passed comparator. // Does not effect the ordering of elements within the container. // Uses timsort. -func GetSortedValues(container Interface, comparator utils.Comparator) []interface{} { +func GetSortedValues(container Container, comparator utils.Comparator) []interface{} { values := container.Values() if len(values) < 2 { return values diff --git a/containers/containers_test.go b/containers/containers_test.go index bef88f4..a2da719 100644 --- a/containers/containers_test.go +++ b/containers/containers_test.go @@ -34,28 +34,28 @@ import ( ) // For testing purposes -type Container struct { +type ContainerTest struct { values []interface{} } -func (container Container) Empty() bool { +func (container ContainerTest) Empty() bool { return len(container.values) == 0 } -func (container Container) Size() int { +func (container ContainerTest) Size() int { return len(container.values) } -func (container Container) Clear() { +func (container ContainerTest) Clear() { container.values = []interface{}{} } -func (container Container) Values() []interface{} { +func (container ContainerTest) Values() []interface{} { return container.values } func TestGetSortedValuesInts(t *testing.T) { - container := Container{} + container := ContainerTest{} container.values = []interface{}{5, 1, 3, 2, 4} values := GetSortedValues(container, utils.IntComparator) for i := 1; i < container.Size(); i++ { @@ -66,7 +66,7 @@ func TestGetSortedValuesInts(t *testing.T) { } func TestGetSortedValuesStrings(t *testing.T) { - container := Container{} + container := ContainerTest{} container.values = []interface{}{"g", "a", "d", "e", "f", "c", "b"} values := GetSortedValues(container, utils.StringComparator) for i := 1; i < container.Size(); i++ { diff --git a/containers/enumerable.go b/containers/enumerable.go new file mode 100644 index 0000000..5824b23 --- /dev/null +++ b/containers/enumerable.go @@ -0,0 +1,86 @@ +/* +Copyright (c) 2015, Emir Pasic +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +// Enumerable functions for ordered containers. +// Ruby's enumerable inspired package. + +package containers + +// Enumerable functions for ordered containers whose values can be fetched by an index. +type EnumerableWithIndex interface { + // Calls the given function once for each element, passing that element's index and value. + Each(func(index int, value interface{})) + + // Invokes the given function once for each element and returns a + // container containing the values returned by the given function. + // TODO need help on how to enforce this in containers (don't want to type assert when chaining) + // Map(func(index int, value interface{}) interface{}) Container + + // Returns a new container containing all elements for which the given function returns a true value. + // TODO need help on how to enforce this in containers (don't want to type assert when chaining) + // Select(func(index int, value interface{}) bool) Container + + // Passes each element of the container to the given function and + // returns true if the function ever returns true for any element. + Any(func(index int, value interface{}) bool) bool + + // Passes each element of the container to the given function and + // returns true if the function returns true for all elements. + All(func(index int, value interface{}) bool) bool + + // 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. + Find(func(index int, value interface{}) bool) (int, interface{}) +} + +// Enumerable functions for ordered containers whose values whose elements are key/value pairs. +type EnumerableWithKey interface { + // Calls the given function once for each element, passing that element's key and value. + Each(func(key interface{}, value interface{})) + + // Invokes the given function once for each element and returns a container + // containing the values returned by the given function as key/value pairs. + // TODO need help on how to enforce this in containers (don't want to type assert when chaining) + // Map(func(key interface{}, value interface{}) (interface{}, interface{})) Container + + // Returns a new container containing all elements for which the given function returns a true value. + // TODO need help on how to enforce this in containers (don't want to type assert when chaining) + // Select(func(key interface{}, value interface{}) bool) Container + + // Passes each element of the container to the given function and + // returns true if the function ever returns true for any element. + Any(func(key interface{}, value interface{}) bool) bool + + // Passes each element of the container to the given function and + // returns true if the function returns true for all elements. + All(func(key interface{}, value interface{}) bool) bool + + // 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. + Find(func(key interface{}, value interface{}) bool) (interface{}, interface{}) +} diff --git a/containers/iterator.go b/containers/iterator.go new file mode 100644 index 0000000..45d0618 --- /dev/null +++ b/containers/iterator.go @@ -0,0 +1,57 @@ +/* +Copyright (c) 2015, Emir Pasic +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +// Stateful iterator pattern for ordered containers. + +package containers + +// Stateful iterator for ordered containers whose values can be fetched by an index. +type IteratorWithIndex interface { + // Moves the iterator to the next element and returns true if there was a next element in the container. + // If Next() returns true, then next element's index and value can be retrieved by Index() and Value(). + // Modifies the state of the iterator. + Next() bool + // Returns the current element's value. + // Does not modify the state of the iterator. + Value() interface{} + // Returns the current element's index. + // Does not modify the state of the iterator. + Index() int +} + +// Stateful iterator for ordered containers whose elements are key value pairs. +type IteratorWithKey interface { + // Moves the iterator to the next element and returns true if there was a next element in the container. + // If Next() returns true, then next element's key and value can be retrieved by Key() and Value(). + // Modifies the state of the iterator. + Next() bool + // Returns the current element's value. + // Does not modify the state of the iterator. + Value() interface{} + // Returns the current element's key. + // Does not modify the state of the iterator. + Key() interface{} +} diff --git a/examples/enumerablewithindex.go b/examples/enumerablewithindex.go new file mode 100644 index 0000000..99f1954 --- /dev/null +++ b/examples/enumerablewithindex.go @@ -0,0 +1,80 @@ +/* +Copyright (c) 2015, Emir Pasic +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +package examples + +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 EnumerableWithIndexTest() { + 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{} { + return value.(int) * value.(int) + }) + printSet("Numbers squared", square) // [ 4 9 16 25 36 49 64 ] + + bigger := set.Any(func(index int, value interface{}) bool { + return value.(int) > 5 + }) + fmt.Println("Set contains a number bigger than 5 is ", bigger) // true + + positive := set.All(func(index int, value interface{}) bool { + return value.(int) > 0 + }) + fmt.Println("All numbers are positive is", positive) // true + + evenNumbersSquared := set.Select(func(index int, value interface{}) bool { + return value.(int)%2 == 0 + }).Map(func(index int, value interface{}) interface{} { + return value.(int) * value.(int) + }) + printSet("Chaining", evenNumbersSquared) // [ 4 16 36 64 ] +} diff --git a/examples/enumerablewithkey.go b/examples/enumerablewithkey.go new file mode 100644 index 0000000..aba2d24 --- /dev/null +++ b/examples/enumerablewithkey.go @@ -0,0 +1,86 @@ +/* +Copyright (c) 2015, Emir Pasic +All rights reserved. + +Redistribution and use in source and binary forms, with or without +modification, are permitted provided that the following conditions are met: + +* Redistributions of source code must retain the above copyright notice, this + list of conditions and the following disclaimer. + +* Redistributions in binary form must reproduce the above copyright notice, + this list of conditions and the following disclaimer in the documentation + and/or other materials provided with the distribution. + +THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" +AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE +IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE +DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE +FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL +DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR +SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER +CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, +OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE +OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. +*/ + +package examples + +import ( + "fmt" + "github.com/emirpasic/gods/maps/treemap" +) + +func printMap(txt string, m *treemap.Map) { + fmt.Print(txt, " { ") + m.Each(func(key interface{}, value interface{}) { + fmt.Print(key, ":", value, " ") + }) + fmt.Println("}") +} + +func EunumerableWithKey() { + m := treemap.NewWithStringComparator() + m.Put("g", 7) + m.Put("f", 6) + m.Put("e", 5) + m.Put("d", 4) + m.Put("c", 3) + m.Put("b", 2) + m.Put("a", 1) + printMap("Initial", m) // { a:1 b:2 c:3 d:4 e:5 f:6 g:7 } + + even := m.Select(func(key interface{}, value interface{}) bool { + return value.(int)%2 == 0 + }) + printMap("Elements with even values", even) // { b:2 d:4 f:6 } + + foundKey, foundValue := m.Find(func(key interface{}, value interface{}) bool { + return value.(int)%2 == 0 && value.(int)%3 == 0 + }) + if foundKey != nil { + fmt.Println("Element with value divisible by 2 and 3 found is", foundValue, "with key", foundKey) // value: 6, index: 4 + } + + square := m.Map(func(key interface{}, value interface{}) (interface{}, interface{}) { + return key.(string) + key.(string), value.(int) * value.(int) + }) + printMap("Elements' values squared and letters duplicated", square) // { aa:1 bb:4 cc:9 dd:16 ee:25 ff:36 gg:49 } + + bigger := m.Any(func(key interface{}, value interface{}) bool { + return value.(int) > 5 + }) + fmt.Println("Map contains element whose value is bigger than 5 is", bigger) // true + + positive := m.All(func(key interface{}, value interface{}) bool { + return value.(int) > 0 + }) + fmt.Println("All map's elements have positive values is", positive) // true + + evenNumbersSquared := m.Select(func(key interface{}, value interface{}) bool { + return value.(int)%2 == 0 + }).Map(func(key interface{}, value interface{}) (interface{}, interface{}) { + return key, value.(int) * value.(int) + }) + printMap("Chaining", evenNumbersSquared) // { b:4 d:16 f:36 } +} diff --git a/lists/arraylist/arraylist.go b/lists/arraylist/arraylist.go index 278f153..cdcd2d9 100644 --- a/lists/arraylist/arraylist.go +++ b/lists/arraylist/arraylist.go @@ -32,13 +32,16 @@ package arraylist import ( "fmt" + "github.com/emirpasic/gods/containers" "github.com/emirpasic/gods/lists" "github.com/emirpasic/gods/utils" "strings" ) func assertInterfaceImplementation() { - var _ lists.Interface = (*List)(nil) + var _ lists.List = (*List)(nil) + var _ containers.EnumerableWithIndex = (*List)(nil) + var _ containers.IteratorWithIndex = (*Iterator)(nil) } type List struct { @@ -175,6 +178,104 @@ func (list *List) Insert(index int, values ...interface{}) { } } +type Iterator struct { + list *List + index int +} + +// Returns a stateful iterator whose values can be fetched by an index. +func (list *List) Iterator() Iterator { + return Iterator{list: list, index: -1} +} + +// Moves the iterator to the next element and returns true if there was a next element in the container. +// If Next() returns true, then next element's index and value can be retrieved by Index() and Value(). +// Modifies the state of the iterator. +func (iterator *Iterator) Next() bool { + iterator.index += 1 + return iterator.list.withinRange(iterator.index) +} + +// Returns the current element's value. +// Does not modify the state of the iterator. +func (iterator *Iterator) Value() interface{} { + return iterator.list.elements[iterator.index] +} + +// Returns the current element's index. +// Does not modify the state of the iterator. +func (iterator *Iterator) Index() int { + return iterator.index +} + +// Calls the given function once for each element, passing that element's index and value. +func (list *List) Each(f func(index int, value interface{})) { + iterator := list.Iterator() + for iterator.Next() { + f(iterator.Index(), iterator.Value()) + } +} + +// Invokes the given function once for each element and returns a +// container containing the values returned by the given function. +func (list *List) Map(f func(index int, value interface{}) interface{}) *List { + newList := &List{} + iterator := list.Iterator() + for iterator.Next() { + newList.Add(f(iterator.Index(), iterator.Value())) + } + return newList +} + +// Returns a new container containing all elements for which the given function returns a true value. +func (list *List) Select(f func(index int, value interface{}) bool) *List { + newList := &List{} + iterator := list.Iterator() + for iterator.Next() { + if f(iterator.Index(), iterator.Value()) { + newList.Add(iterator.Value()) + } + } + return newList +} + +// Passes each element of the collection to the given function and +// returns true if the function ever returns true for any element. +func (list *List) Any(f func(index int, value interface{}) bool) bool { + iterator := list.Iterator() + for iterator.Next() { + if f(iterator.Index(), iterator.Value()) { + return true + } + } + return false +} + +// Passes each element of the collection to the given function and +// returns true if the function returns true for all elements. +func (list *List) All(f func(index int, value interface{}) bool) bool { + iterator := list.Iterator() + for iterator.Next() { + if !f(iterator.Index(), iterator.Value()) { + return false + } + } + return true +} + +// 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. +func (list *List) Find(f func(index int, value interface{}) bool) (int, interface{}) { + iterator := list.Iterator() + for iterator.Next() { + if f(iterator.Index(), iterator.Value()) { + return iterator.Index(), iterator.Value() + } + } + return -1, nil +} + func (list *List) String() string { str := "ArrayList\n" values := []string{} @@ -216,5 +317,4 @@ func (list *List) shrink() { if list.size <= int(float32(currentCapacity)*SHRINK_FACTOR) { list.resize(list.size) } - } diff --git a/lists/arraylist/arraylist_test.go b/lists/arraylist/arraylist_test.go index ab07f67..c3f0c58 100644 --- a/lists/arraylist/arraylist_test.go +++ b/lists/arraylist/arraylist_test.go @@ -133,7 +133,132 @@ func TestArrayList(t *testing.T) { if actualValue, expectedValue := fmt.Sprintf("%s%s%s%s%s%s%s%s%s%s%s", list.Values()...), "abcdefghijk"; actualValue != expectedValue { t.Errorf("Got %v expected %v", actualValue, expectedValue) } +} + +func TestArrayListEnumerableAndIterator(t *testing.T) { + list := New() + list.Add("a", "b", "c") + + // Each + list.Each(func(index int, value interface{}) { + switch index { + case 0: + if actualValue, expectedValue := value, "a"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + case 1: + if actualValue, expectedValue := value, "b"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + case 2: + if actualValue, expectedValue := value, "c"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + default: + t.Errorf("Too many") + } + }) + + // Map + mappedList := list.Map(func(index int, value interface{}) interface{} { + return "mapped: " + value.(string) + }) + if actualValue, _ := mappedList.Get(0); actualValue != "mapped: a" { + t.Errorf("Got %v expected %v", actualValue, "mapped: a") + } + if actualValue, _ := mappedList.Get(1); actualValue != "mapped: b" { + t.Errorf("Got %v expected %v", actualValue, "mapped: b") + } + if actualValue, _ := mappedList.Get(2); actualValue != "mapped: c" { + t.Errorf("Got %v expected %v", actualValue, "mapped: c") + } + if mappedList.Size() != 3 { + t.Errorf("Got %v expected %v", mappedList.Size(), 3) + } + + // Select + selectedList := list.Select(func(index int, value interface{}) bool { + return value.(string) >= "a" && value.(string) <= "b" + }) + if actualValue, _ := selectedList.Get(0); actualValue != "a" { + t.Errorf("Got %v expected %v", actualValue, "value: a") + } + if actualValue, _ := selectedList.Get(1); actualValue != "b" { + t.Errorf("Got %v expected %v", actualValue, "value: b") + } + if selectedList.Size() != 2 { + t.Errorf("Got %v expected %v", selectedList.Size(), 3) + } + // Any + any := list.Any(func(index int, value interface{}) bool { + return value.(string) == "c" + }) + if any != true { + t.Errorf("Got %v expected %v", any, true) + } + any = list.Any(func(index int, value interface{}) bool { + return value.(string) == "x" + }) + if any != false { + t.Errorf("Got %v expected %v", any, false) + } + + // All + all := list.All(func(index int, value interface{}) bool { + return value.(string) >= "a" && value.(string) <= "c" + }) + if all != true { + t.Errorf("Got %v expected %v", all, true) + } + all = list.All(func(index int, value interface{}) bool { + return value.(string) >= "a" && value.(string) <= "b" + }) + if all != false { + t.Errorf("Got %v expected %v", all, false) + } + + // Find + foundIndex, foundValue := list.Find(func(index int, value interface{}) bool { + return value.(string) == "c" + }) + if foundValue != "c" || foundIndex != 2 { + t.Errorf("Got %v at %v expected %v at %v", foundValue, foundIndex, "c", 2) + } + foundIndex, foundValue = list.Find(func(index int, value interface{}) bool { + return value.(string) == "x" + }) + if foundValue != nil || foundIndex != -1 { + t.Errorf("Got %v at %v expected %v at %v", foundValue, foundIndex, nil, nil) + } + + // Iterator + it := list.Iterator() + for it.Next() { + index := it.Index() + value := it.Value() + switch index { + case 0: + if actualValue, expectedValue := value, "a"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + case 1: + if actualValue, expectedValue := value, "b"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + case 2: + if actualValue, expectedValue := value, "c"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + default: + t.Errorf("Too many") + } + } + list.Clear() + it = list.Iterator() + for it.Next() { + t.Errorf("Shouldn't iterate on empty list") + } } func BenchmarkArrayList(b *testing.B) { diff --git a/lists/doublylinkedlist/doublylinkedlist.go b/lists/doublylinkedlist/doublylinkedlist.go index 2a97756..73f7e59 100644 --- a/lists/doublylinkedlist/doublylinkedlist.go +++ b/lists/doublylinkedlist/doublylinkedlist.go @@ -32,13 +32,16 @@ package doublylinkedlist import ( "fmt" + "github.com/emirpasic/gods/containers" "github.com/emirpasic/gods/lists" "github.com/emirpasic/gods/utils" "strings" ) func assertInterfaceImplementation() { - var _ lists.Interface = (*List)(nil) + var _ lists.List = (*List)(nil) + var _ containers.EnumerableWithIndex = (*List)(nil) + var _ containers.IteratorWithIndex = (*Iterator)(nil) } type List struct { @@ -297,6 +300,114 @@ func (list *List) Insert(index int, values ...interface{}) { } } +type Iterator struct { + list *List + index int + element *element +} + +// Returns a stateful iterator whose values can be fetched by an index. +func (list *List) Iterator() Iterator { + return Iterator{list: list, index: -1, element: nil} +} + +// Moves the iterator to the next element and returns true if there was a next element in the container. +// If Next() returns true, then next element's index and value can be retrieved by Index() and Value(). +// Modifies the state of the iterator. +func (iterator *Iterator) Next() bool { + iterator.index += 1 + if !iterator.list.withinRange(iterator.index) { + iterator.element = nil + return false + } + if iterator.element != nil { + iterator.element = iterator.element.next + } else { + iterator.element = iterator.list.first + } + return true +} + +// Returns the current element's value. +// Does not modify the state of the iterator. +func (iterator *Iterator) Value() interface{} { + return iterator.element.value +} + +// Returns the current element's index. +// Does not modify the state of the iterator. +func (iterator *Iterator) Index() int { + return iterator.index +} + +// Calls the given function once for each element, passing that element's index and value. +func (list *List) Each(f func(index int, value interface{})) { + iterator := list.Iterator() + for iterator.Next() { + f(iterator.Index(), iterator.Value()) + } +} + +// Invokes the given function once for each element and returns a +// container containing the values returned by the given function. +func (list *List) Map(f func(index int, value interface{}) interface{}) *List { + newList := &List{} + iterator := list.Iterator() + for iterator.Next() { + newList.Add(f(iterator.Index(), iterator.Value())) + } + return newList +} + +// Returns a new container containing all elements for which the given function returns a true value. +func (list *List) Select(f func(index int, value interface{}) bool) *List { + newList := &List{} + iterator := list.Iterator() + for iterator.Next() { + if f(iterator.Index(), iterator.Value()) { + newList.Add(iterator.Value()) + } + } + return newList +} + +// Passes each element of the container to the given function and +// returns true if the function ever returns true for any element. +func (list *List) Any(f func(index int, value interface{}) bool) bool { + iterator := list.Iterator() + for iterator.Next() { + if f(iterator.Index(), iterator.Value()) { + return true + } + } + return false +} + +// Passes each element of the container to the given function and +// returns true if the function returns true for all elements. +func (list *List) All(f func(index int, value interface{}) bool) bool { + iterator := list.Iterator() + for iterator.Next() { + if !f(iterator.Index(), iterator.Value()) { + return false + } + } + return true +} + +// 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. +func (list *List) Find(f func(index int, value interface{}) bool) (index int, value interface{}) { + iterator := list.Iterator() + for iterator.Next() { + if f(iterator.Index(), iterator.Value()) { + return iterator.Index(), iterator.Value() + } + } + return -1, nil +} + func (list *List) String() string { str := "DoublyLinkedList\n" values := []string{} diff --git a/lists/doublylinkedlist/doublylinkedlist_test.go b/lists/doublylinkedlist/doublylinkedlist_test.go index 528b00f..5e8331d 100644 --- a/lists/doublylinkedlist/doublylinkedlist_test.go +++ b/lists/doublylinkedlist/doublylinkedlist_test.go @@ -135,7 +135,132 @@ func TestDoublyLinkedList(t *testing.T) { if actualValue, expectedValue := fmt.Sprintf("%s%s%s%s%s%s%s%s%s%s%s", list.Values()...), "abcdefghijk"; actualValue != expectedValue { t.Errorf("Got %v expected %v", actualValue, expectedValue) } +} + +func TestDoublyLinkedListEnumerableAndIterator(t *testing.T) { + list := New() + list.Add("a", "b", "c") + + // Each + list.Each(func(index int, value interface{}) { + switch index { + case 0: + if actualValue, expectedValue := value, "a"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + case 1: + if actualValue, expectedValue := value, "b"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + case 2: + if actualValue, expectedValue := value, "c"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + default: + t.Errorf("Too many") + } + }) + + // Map + mappedList := list.Map(func(index int, value interface{}) interface{} { + return "mapped: " + value.(string) + }) + if actualValue, _ := mappedList.Get(0); actualValue != "mapped: a" { + t.Errorf("Got %v expected %v", actualValue, "mapped: a") + } + if actualValue, _ := mappedList.Get(1); actualValue != "mapped: b" { + t.Errorf("Got %v expected %v", actualValue, "mapped: b") + } + if actualValue, _ := mappedList.Get(2); actualValue != "mapped: c" { + t.Errorf("Got %v expected %v", actualValue, "mapped: c") + } + if mappedList.Size() != 3 { + t.Errorf("Got %v expected %v", mappedList.Size(), 3) + } + + // Select + selectedList := list.Select(func(index int, value interface{}) bool { + return value.(string) >= "a" && value.(string) <= "b" + }) + if actualValue, _ := selectedList.Get(0); actualValue != "a" { + t.Errorf("Got %v expected %v", actualValue, "value: a") + } + if actualValue, _ := selectedList.Get(1); actualValue != "b" { + t.Errorf("Got %v expected %v", actualValue, "value: b") + } + if selectedList.Size() != 2 { + t.Errorf("Got %v expected %v", selectedList.Size(), 3) + } + // Any + any := list.Any(func(index int, value interface{}) bool { + return value.(string) == "c" + }) + if any != true { + t.Errorf("Got %v expected %v", any, true) + } + any = list.Any(func(index int, value interface{}) bool { + return value.(string) == "x" + }) + if any != false { + t.Errorf("Got %v expected %v", any, false) + } + + // All + all := list.All(func(index int, value interface{}) bool { + return value.(string) >= "a" && value.(string) <= "c" + }) + if all != true { + t.Errorf("Got %v expected %v", all, true) + } + all = list.All(func(index int, value interface{}) bool { + return value.(string) >= "a" && value.(string) <= "b" + }) + if all != false { + t.Errorf("Got %v expected %v", all, false) + } + + // Find + foundIndex, foundValue := list.Find(func(index int, value interface{}) bool { + return value.(string) == "c" + }) + if foundValue != "c" || foundIndex != 2 { + t.Errorf("Got %v at %v expected %v at %v", foundValue, foundIndex, "c", 2) + } + foundIndex, foundValue = list.Find(func(index int, value interface{}) bool { + return value.(string) == "x" + }) + if foundValue != nil || foundIndex != -1 { + t.Errorf("Got %v at %v expected %v at %v", foundValue, foundIndex, nil, nil) + } + + // Iterator + it := list.Iterator() + for it.Next() { + index := it.Index() + value := it.Value() + switch index { + case 0: + if actualValue, expectedValue := value, "a"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + case 1: + if actualValue, expectedValue := value, "b"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + case 2: + if actualValue, expectedValue := value, "c"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + default: + t.Errorf("Too many") + } + } + list.Clear() + it = list.Iterator() + for it.Next() { + t.Errorf("Shouldn't iterate on empty list") + } } func BenchmarkDoublyLinkedList(b *testing.B) { diff --git a/lists/lists.go b/lists/lists.go index 5a83a4c..8bc0575 100644 --- a/lists/lists.go +++ b/lists/lists.go @@ -23,7 +23,7 @@ import ( "github.com/emirpasic/gods/utils" ) -type Interface interface { +type List interface { Get(index int) (interface{}, bool) Remove(index int) Add(values ...interface{}) @@ -32,7 +32,7 @@ type Interface interface { Swap(index1, index2 int) Insert(index int, values ...interface{}) - containers.Interface + containers.Container // Empty() bool // Size() int // Clear() diff --git a/lists/singlylinkedlist/singlylinkedlist.go b/lists/singlylinkedlist/singlylinkedlist.go index f993c39..e71a36f 100644 --- a/lists/singlylinkedlist/singlylinkedlist.go +++ b/lists/singlylinkedlist/singlylinkedlist.go @@ -32,13 +32,16 @@ package singlylinkedlist import ( "fmt" + "github.com/emirpasic/gods/containers" "github.com/emirpasic/gods/lists" "github.com/emirpasic/gods/utils" "strings" ) func assertInterfaceImplementation() { - var _ lists.Interface = (*List)(nil) + var _ lists.List = (*List)(nil) + var _ containers.EnumerableWithIndex = (*List)(nil) + var _ containers.IteratorWithIndex = (*Iterator)(nil) } type List struct { @@ -267,6 +270,114 @@ func (list *List) Insert(index int, values ...interface{}) { } } +type Iterator struct { + list *List + index int + element *element +} + +// Returns a stateful iterator whose values can be fetched by an index. +func (list *List) Iterator() Iterator { + return Iterator{list: list, index: -1, element: nil} +} + +// Moves the iterator to the next element and returns true if there was a next element in the container. +// If Next() returns true, then next element's index and value can be retrieved by Index() and Value(). +// Modifies the state of the iterator. +func (iterator *Iterator) Next() bool { + iterator.index += 1 + if !iterator.list.withinRange(iterator.index) { + iterator.element = nil + return false + } + if iterator.element != nil { + iterator.element = iterator.element.next + } else { + iterator.element = iterator.list.first + } + return true +} + +// Returns the current element's value. +// Does not modify the state of the iterator. +func (iterator *Iterator) Value() interface{} { + return iterator.element.value +} + +// Returns the current element's index. +// Does not modify the state of the iterator. +func (iterator *Iterator) Index() int { + return iterator.index +} + +// Calls the given function once for each element, passing that element's index and value. +func (list *List) Each(f func(index int, value interface{})) { + iterator := list.Iterator() + for iterator.Next() { + f(iterator.Index(), iterator.Value()) + } +} + +// Invokes the given function once for each element and returns a +// container containing the values returned by the given function. +func (list *List) Map(f func(index int, value interface{}) interface{}) *List { + newList := &List{} + iterator := list.Iterator() + for iterator.Next() { + newList.Add(f(iterator.Index(), iterator.Value())) + } + return newList +} + +// Returns a new container containing all elements for which the given function returns a true value. +func (list *List) Select(f func(index int, value interface{}) bool) *List { + newList := &List{} + iterator := list.Iterator() + for iterator.Next() { + if f(iterator.Index(), iterator.Value()) { + newList.Add(iterator.Value()) + } + } + return newList +} + +// Passes each element of the container to the given function and +// returns true if the function ever returns true for any element. +func (list *List) Any(f func(index int, value interface{}) bool) bool { + iterator := list.Iterator() + for iterator.Next() { + if f(iterator.Index(), iterator.Value()) { + return true + } + } + return false +} + +// Passes each element of the container to the given function and +// returns true if the function returns true for all elements. +func (list *List) All(f func(index int, value interface{}) bool) bool { + iterator := list.Iterator() + for iterator.Next() { + if !f(iterator.Index(), iterator.Value()) { + return false + } + } + return true +} + +// 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. +func (list *List) Find(f func(index int, value interface{}) bool) (index int, value interface{}) { + iterator := list.Iterator() + for iterator.Next() { + if f(iterator.Index(), iterator.Value()) { + return iterator.Index(), iterator.Value() + } + } + return -1, nil +} + func (list *List) String() string { str := "SinglyLinkedList\n" values := []string{} diff --git a/lists/singlylinkedlist/singlylinkedlist_test.go b/lists/singlylinkedlist/singlylinkedlist_test.go index df08466..d5879c3 100644 --- a/lists/singlylinkedlist/singlylinkedlist_test.go +++ b/lists/singlylinkedlist/singlylinkedlist_test.go @@ -135,7 +135,132 @@ func TestSinglyLinkedList(t *testing.T) { if actualValue, expectedValue := fmt.Sprintf("%s%s%s%s%s%s%s%s%s%s%s", list.Values()...), "abcdefghijk"; actualValue != expectedValue { t.Errorf("Got %v expected %v", actualValue, expectedValue) } +} + +func TestSinglyLinkedListEnumerableAndIterator(t *testing.T) { + list := New() + list.Add("a", "b", "c") + + // Each + list.Each(func(index int, value interface{}) { + switch index { + case 0: + if actualValue, expectedValue := value, "a"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + case 1: + if actualValue, expectedValue := value, "b"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + case 2: + if actualValue, expectedValue := value, "c"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + default: + t.Errorf("Too many") + } + }) + + // Map + mappedList := list.Map(func(index int, value interface{}) interface{} { + return "mapped: " + value.(string) + }) + if actualValue, _ := mappedList.Get(0); actualValue != "mapped: a" { + t.Errorf("Got %v expected %v", actualValue, "mapped: a") + } + if actualValue, _ := mappedList.Get(1); actualValue != "mapped: b" { + t.Errorf("Got %v expected %v", actualValue, "mapped: b") + } + if actualValue, _ := mappedList.Get(2); actualValue != "mapped: c" { + t.Errorf("Got %v expected %v", actualValue, "mapped: c") + } + if mappedList.Size() != 3 { + t.Errorf("Got %v expected %v", mappedList.Size(), 3) + } + + // Select + selectedList := list.Select(func(index int, value interface{}) bool { + return value.(string) >= "a" && value.(string) <= "b" + }) + if actualValue, _ := selectedList.Get(0); actualValue != "a" { + t.Errorf("Got %v expected %v", actualValue, "value: a") + } + if actualValue, _ := selectedList.Get(1); actualValue != "b" { + t.Errorf("Got %v expected %v", actualValue, "value: b") + } + if selectedList.Size() != 2 { + t.Errorf("Got %v expected %v", selectedList.Size(), 3) + } + // Any + any := list.Any(func(index int, value interface{}) bool { + return value.(string) == "c" + }) + if any != true { + t.Errorf("Got %v expected %v", any, true) + } + any = list.Any(func(index int, value interface{}) bool { + return value.(string) == "x" + }) + if any != false { + t.Errorf("Got %v expected %v", any, false) + } + + // All + all := list.All(func(index int, value interface{}) bool { + return value.(string) >= "a" && value.(string) <= "c" + }) + if all != true { + t.Errorf("Got %v expected %v", all, true) + } + all = list.All(func(index int, value interface{}) bool { + return value.(string) >= "a" && value.(string) <= "b" + }) + if all != false { + t.Errorf("Got %v expected %v", all, false) + } + + // Find + foundIndex, foundValue := list.Find(func(index int, value interface{}) bool { + return value.(string) == "c" + }) + if foundValue != "c" || foundIndex != 2 { + t.Errorf("Got %v at %v expected %v at %v", foundValue, foundIndex, "c", 2) + } + foundIndex, foundValue = list.Find(func(index int, value interface{}) bool { + return value.(string) == "x" + }) + if foundValue != nil || foundIndex != -1 { + t.Errorf("Got %v at %v expected %v at %v", foundValue, foundIndex, nil, nil) + } + + // Iterator + it := list.Iterator() + for it.Next() { + index := it.Index() + value := it.Value() + switch index { + case 0: + if actualValue, expectedValue := value, "a"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + case 1: + if actualValue, expectedValue := value, "b"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + case 2: + if actualValue, expectedValue := value, "c"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + default: + t.Errorf("Too many") + } + } + list.Clear() + it = list.Iterator() + for it.Next() { + t.Errorf("Shouldn't iterate on empty list") + } } func BenchmarkSinglyLinkedList(b *testing.B) { diff --git a/maps/hashmap/hashmap.go b/maps/hashmap/hashmap.go index 247cc01..3033f6b 100644 --- a/maps/hashmap/hashmap.go +++ b/maps/hashmap/hashmap.go @@ -37,7 +37,7 @@ import ( ) func assertInterfaceImplementation() { - var _ maps.Interface = (*Map)(nil) + var _ maps.Map = (*Map)(nil) } type Map struct { diff --git a/maps/maps.go b/maps/maps.go index eddcc20..22fcf73 100644 --- a/maps/maps.go +++ b/maps/maps.go @@ -28,13 +28,13 @@ package maps import "github.com/emirpasic/gods/containers" -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() diff --git a/maps/treemap/treemap.go b/maps/treemap/treemap.go index 6d228cb..b18f293 100644 --- a/maps/treemap/treemap.go +++ b/maps/treemap/treemap.go @@ -32,13 +32,16 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. package treemap import ( + "github.com/emirpasic/gods/containers" "github.com/emirpasic/gods/maps" rbt "github.com/emirpasic/gods/trees/redblacktree" "github.com/emirpasic/gods/utils" ) func assertInterfaceImplementation() { - var _ maps.Interface = (*Map)(nil) + var _ maps.Map = (*Map)(nil) + var _ containers.EnumerableWithKey = (*Map)(nil) + var _ containers.IteratorWithKey = (*Iterator)(nil) } type Map struct { @@ -122,6 +125,103 @@ func (m *Map) Max() (key interface{}, value interface{}) { return nil, nil } +type Iterator struct { + iterator rbt.Iterator +} + +// Returns a stateful iterator whose elements are key/value pairs. +func (m *Map) Iterator() Iterator { + return Iterator{iterator: m.tree.Iterator()} +} + +// Moves the iterator to the next element and returns true if there was a next element in the container. +// If Next() returns true, then next element's key and value can be retrieved by Key() and Value(). +// Modifies the state of the iterator. +func (iterator *Iterator) Next() bool { + return iterator.iterator.Next() +} + +// Returns the current element's value. +// Does not modify the state of the iterator. +func (iterator *Iterator) Value() interface{} { + return iterator.iterator.Value() +} + +// Returns the current element's key. +// Does not modify the state of the iterator. +func (iterator *Iterator) Key() interface{} { + return iterator.iterator.Key() +} + +// Calls the given function once for each element, passing that element's key and value. +func (m *Map) Each(f func(key interface{}, value interface{})) { + iterator := m.Iterator() + for iterator.Next() { + f(iterator.Key(), iterator.Value()) + } +} + +// Invokes the given function once for each element and returns a container +// containing the values returned by the given function as key/value pairs. +func (m *Map) Map(f func(key1 interface{}, value1 interface{}) (interface{}, interface{})) *Map { + newMap := &Map{tree: rbt.NewWith(m.tree.Comparator)} + iterator := m.Iterator() + for iterator.Next() { + key2, value2 := f(iterator.Key(), iterator.Value()) + newMap.Put(key2, value2) + } + return newMap +} + +// Returns a new container containing all elements for which the given function returns a true value. +func (m *Map) Select(f func(key interface{}, value interface{}) bool) *Map { + newMap := &Map{tree: rbt.NewWith(m.tree.Comparator)} + iterator := m.Iterator() + for iterator.Next() { + if f(iterator.Key(), iterator.Value()) { + newMap.Put(iterator.Key(), iterator.Value()) + } + } + return newMap +} + +// Passes each element of the container to the given function and +// returns true if the function ever returns true for any element. +func (m *Map) Any(f func(key interface{}, value interface{}) bool) bool { + iterator := m.Iterator() + for iterator.Next() { + if f(iterator.Key(), iterator.Value()) { + return true + } + } + return false +} + +// Passes each element of the container to the given function and +// returns true if the function returns true for all elements. +func (m *Map) All(f func(key interface{}, value interface{}) bool) bool { + iterator := m.Iterator() + for iterator.Next() { + if !f(iterator.Key(), iterator.Value()) { + return false + } + } + return true +} + +// 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. +func (m *Map) Find(f func(key interface{}, value interface{}) bool) (interface{}, interface{}) { + iterator := m.Iterator() + for iterator.Next() { + if f(iterator.Key(), iterator.Value()) { + return iterator.Key(), iterator.Value() + } + } + return nil, nil +} + func (m *Map) String() string { str := "TreeMap\n" str += m.tree.String() diff --git a/maps/treemap/treemap_test.go b/maps/treemap/treemap_test.go index c48c454..4335b7f 100644 --- a/maps/treemap/treemap_test.go +++ b/maps/treemap/treemap_test.go @@ -179,6 +179,139 @@ func TestTreeMap(t *testing.T) { } } +func TestTreeMapEnumerableAndIterator(t *testing.T) { + m := NewWithStringComparator() + m.Put("c", 3) + m.Put("a", 1) + m.Put("b", 2) + + // Each + count := 0 + m.Each(func(key interface{}, value interface{}) { + count += 1 + if actualValue, expectedValue := count, value; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + switch value { + case 1: + if actualValue, expectedValue := key, "a"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + case 2: + if actualValue, expectedValue := key, "b"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + case 3: + if actualValue, expectedValue := key, "c"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + default: + t.Errorf("Too many") + } + }) + + // Map + mappedMap := m.Map(func(key1 interface{}, value1 interface{}) (key2 interface{}, value2 interface{}) { + return key1, "mapped: " + key1.(string) + }) + if actualValue, _ := mappedMap.Get("a"); actualValue != "mapped: a" { + t.Errorf("Got %v expected %v", actualValue, "mapped: a") + } + if actualValue, _ := mappedMap.Get("b"); actualValue != "mapped: b" { + t.Errorf("Got %v expected %v", actualValue, "mapped: b") + } + if actualValue, _ := mappedMap.Get("c"); actualValue != "mapped: c" { + t.Errorf("Got %v expected %v", actualValue, "mapped: c") + } + if mappedMap.Size() != 3 { + t.Errorf("Got %v expected %v", mappedMap.Size(), 3) + } + + // Select + selectedMap := m.Select(func(key interface{}, value interface{}) bool { + return key.(string) >= "a" && key.(string) <= "b" + }) + if actualValue, _ := selectedMap.Get("a"); actualValue != 1 { + t.Errorf("Got %v expected %v", actualValue, "value: a") + } + if actualValue, _ := selectedMap.Get("b"); actualValue != 2 { + t.Errorf("Got %v expected %v", actualValue, "value: b") + } + if selectedMap.Size() != 2 { + t.Errorf("Got %v expected %v", selectedMap.Size(), 3) + } + + // Any + any := m.Any(func(key interface{}, value interface{}) bool { + return value.(int) == 3 + }) + if any != true { + t.Errorf("Got %v expected %v", any, true) + } + any = m.Any(func(key interface{}, value interface{}) bool { + return value.(int) == 4 + }) + if any != false { + t.Errorf("Got %v expected %v", any, false) + } + + // All + all := m.All(func(key interface{}, value interface{}) bool { + return key.(string) >= "a" && key.(string) <= "c" + }) + if all != true { + t.Errorf("Got %v expected %v", all, true) + } + all = m.All(func(key interface{}, value interface{}) bool { + return key.(string) >= "a" && key.(string) <= "b" + }) + if all != false { + t.Errorf("Got %v expected %v", all, false) + } + + // Find + foundKey, foundValue := m.Find(func(key interface{}, value interface{}) bool { + return key.(string) == "c" + }) + if foundKey != "c" || foundValue != 3 { + t.Errorf("Got %v -> %v expected %v -> %v", foundKey, foundValue, "c", 3) + } + foundKey, foundValue = m.Find(func(key interface{}, value interface{}) bool { + return key.(string) == "x" + }) + if foundKey != nil || foundValue != nil { + t.Errorf("Got %v at %v expected %v at %v", foundValue, foundKey, nil, nil) + } + + // Iterator + it := m.Iterator() + for it.Next() { + key := it.Key() + value := it.Value() + switch key { + case "a": + if actualValue, expectedValue := value, 1; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + case "b": + if actualValue, expectedValue := value, 2; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + case "c": + if actualValue, expectedValue := value, 3; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + default: + t.Errorf("Too many") + } + } + m.Clear() + it = m.Iterator() + for it.Next() { + t.Errorf("Shouldn't iterate on empty map") + } +} + func BenchmarkTreeMap(b *testing.B) { for i := 0; i < b.N; i++ { m := NewWithIntComparator() diff --git a/sets/hashset/hashset.go b/sets/hashset/hashset.go index dfd1069..54d219b 100644 --- a/sets/hashset/hashset.go +++ b/sets/hashset/hashset.go @@ -37,7 +37,7 @@ import ( ) func assertInterfaceImplementation() { - var _ sets.Interface = (*Set)(nil) + var _ sets.Set = (*Set)(nil) } type Set struct { diff --git a/sets/sets.go b/sets/sets.go index 2a6e2dc..6ced903 100644 --- a/sets/sets.go +++ b/sets/sets.go @@ -20,12 +20,12 @@ package sets import "github.com/emirpasic/gods/containers" -type Interface interface { +type Set interface { Add(elements ...interface{}) Remove(elements ...interface{}) Contains(elements ...interface{}) bool - containers.Interface + containers.Container // Empty() bool // Size() int // Clear() diff --git a/sets/treeset/treeset.go b/sets/treeset/treeset.go index 9236eb1..750e264 100644 --- a/sets/treeset/treeset.go +++ b/sets/treeset/treeset.go @@ -24,6 +24,7 @@ package treeset import ( "fmt" + "github.com/emirpasic/gods/containers" "github.com/emirpasic/gods/sets" rbt "github.com/emirpasic/gods/trees/redblacktree" "github.com/emirpasic/gods/utils" @@ -31,7 +32,9 @@ import ( ) func assertInterfaceImplementation() { - var _ sets.Interface = (*Set)(nil) + var _ sets.Set = (*Set)(nil) + var _ containers.EnumerableWithIndex = (*Set)(nil) + var _ containers.IteratorWithIndex = (*Iterator)(nil) } type Set struct { @@ -69,7 +72,7 @@ func (set *Set) Remove(items ...interface{}) { } } -// Check wether items (one or more) are present in the set. +// Check weather items (one or more) are present in the set. // All items have to be present in the set for the method to return true. // Returns true if no arguments are passed at all, i.e. set is always superset of empty set. func (set *Set) Contains(items ...interface{}) bool { @@ -101,6 +104,104 @@ func (set *Set) Values() []interface{} { return set.tree.Keys() } +type Iterator struct { + index int + iterator rbt.Iterator +} + +// Returns a stateful iterator whose values can be fetched by an index. +func (set *Set) Iterator() Iterator { + return Iterator{index: -1, iterator: set.tree.Iterator()} +} + +// Moves the iterator to the next element and returns true if there was a next element in the container. +// If Next() returns true, then next element's index and value can be retrieved by Index() and Value(). +// Modifies the state of the iterator. +func (iterator *Iterator) Next() bool { + iterator.index += 1 + return iterator.iterator.Next() +} + +// Returns the current element's value. +// Does not modify the state of the iterator. +func (iterator *Iterator) Value() interface{} { + return iterator.iterator.Key() +} + +// Returns the current element's index. +// Does not modify the state of the iterator. +func (iterator *Iterator) Index() int { + return iterator.index +} + +// Calls the given function once for each element, passing that element's index and value. +func (set *Set) Each(f func(index int, value interface{})) { + iterator := set.Iterator() + for iterator.Next() { + f(iterator.Index(), iterator.Value()) + } +} + +// Invokes the given function once for each element and returns a +// container containing the values returned by the given function. +func (set *Set) Map(f func(index int, value interface{}) interface{}) *Set { + newSet := &Set{tree: rbt.NewWith(set.tree.Comparator)} + iterator := set.Iterator() + for iterator.Next() { + newSet.Add(f(iterator.Index(), iterator.Value())) + } + return newSet +} + +// Returns a new container containing all elements for which the given function returns a true value. +func (set *Set) Select(f func(index int, value interface{}) bool) *Set { + newSet := &Set{tree: rbt.NewWith(set.tree.Comparator)} + iterator := set.Iterator() + for iterator.Next() { + if f(iterator.Index(), iterator.Value()) { + newSet.Add(iterator.Value()) + } + } + return newSet +} + +// Passes each element of the container to the given function and +// returns true if the function ever returns true for any element. +func (set *Set) Any(f func(index int, value interface{}) bool) bool { + iterator := set.Iterator() + for iterator.Next() { + if f(iterator.Index(), iterator.Value()) { + return true + } + } + return false +} + +// Passes each element of the container to the given function and +// returns true if the function returns true for all elements. +func (set *Set) All(f func(index int, value interface{}) bool) bool { + iterator := set.Iterator() + for iterator.Next() { + if !f(iterator.Index(), iterator.Value()) { + return false + } + } + return true +} + +// 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. +func (set *Set) Find(f func(index int, value interface{}) bool) (int, interface{}) { + iterator := set.Iterator() + for iterator.Next() { + if f(iterator.Index(), iterator.Value()) { + return iterator.Index(), iterator.Value() + } + } + return -1, nil +} + func (set *Set) String() string { str := "TreeSet\n" items := []string{} diff --git a/sets/treeset/treeset_test.go b/sets/treeset/treeset_test.go index b033a7b..db30724 100644 --- a/sets/treeset/treeset_test.go +++ b/sets/treeset/treeset_test.go @@ -82,7 +82,130 @@ func TestTreeSet(t *testing.T) { if actualValue := set.Empty(); actualValue != true { t.Errorf("Got %v expected %v", actualValue, true) } +} + +func TestTreeSetEnumerableAndIterator(t *testing.T) { + set := NewWithStringComparator() + set.Add("c", "a", "b") + + // Each + set.Each(func(index int, value interface{}) { + switch index { + case 0: + if actualValue, expectedValue := value, "a"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + case 1: + if actualValue, expectedValue := value, "b"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + case 2: + if actualValue, expectedValue := value, "c"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + default: + t.Errorf("Too many") + } + }) + + // Map + mappedSet := set.Map(func(index int, value interface{}) interface{} { + return "mapped: " + value.(string) + }) + if actualValue, expectedValue := mappedSet.Contains("mapped: a", "mapped: b", "mapped: c"), true; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + if actualValue, expectedValue := mappedSet.Contains("mapped: a", "mapped: b", "mapped: x"), false; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + if mappedSet.Size() != 3 { + t.Errorf("Got %v expected %v", mappedSet.Size(), 3) + } + + // Select + selectedSet := set.Select(func(index int, value interface{}) bool { + return value.(string) >= "a" && value.(string) <= "b" + }) + if actualValue, expectedValue := selectedSet.Contains("a", "b"), true; actualValue != expectedValue { + fmt.Println("A: ", mappedSet.Contains("b")) + t.Errorf("Got %v (%v) expected %v (%v)", actualValue, selectedSet.Values(), expectedValue, "[a b]") + } + if actualValue, expectedValue := selectedSet.Contains("a", "b", "c"), false; actualValue != expectedValue { + t.Errorf("Got %v (%v) expected %v (%v)", actualValue, selectedSet.Values(), expectedValue, "[a b]") + } + if selectedSet.Size() != 2 { + t.Errorf("Got %v expected %v", selectedSet.Size(), 3) + } + + // Any + any := set.Any(func(index int, value interface{}) bool { + return value.(string) == "c" + }) + if any != true { + t.Errorf("Got %v expected %v", any, true) + } + any = set.Any(func(index int, value interface{}) bool { + return value.(string) == "x" + }) + if any != false { + t.Errorf("Got %v expected %v", any, false) + } + + // All + all := set.All(func(index int, value interface{}) bool { + return value.(string) >= "a" && value.(string) <= "c" + }) + if all != true { + t.Errorf("Got %v expected %v", all, true) + } + all = set.All(func(index int, value interface{}) bool { + return value.(string) >= "a" && value.(string) <= "b" + }) + if all != false { + t.Errorf("Got %v expected %v", all, false) + } + // Find + foundIndex, foundValue := set.Find(func(index int, value interface{}) bool { + return value.(string) == "c" + }) + if foundValue != "c" || foundIndex != 2 { + t.Errorf("Got %v at %v expected %v at %v", foundValue, foundIndex, "c", 2) + } + foundIndex, foundValue = set.Find(func(index int, value interface{}) bool { + return value.(string) == "x" + }) + if foundValue != nil || foundIndex != -1 { + t.Errorf("Got %v at %v expected %v at %v", foundValue, foundIndex, nil, nil) + } + + // Iterator + it := set.Iterator() + for it.Next() { + index := it.Index() + value := it.Value() + switch index { + case 0: + if actualValue, expectedValue := value, "a"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + case 1: + if actualValue, expectedValue := value, "b"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + case 2: + if actualValue, expectedValue := value, "c"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + default: + t.Errorf("Too many") + } + } + set.Clear() + it = set.Iterator() + for it.Next() { + t.Errorf("Shouldn't iterate on empty set") + } } func BenchmarkTreeSet(b *testing.B) { diff --git a/stacks/arraystack/arraystack.go b/stacks/arraystack/arraystack.go index bb3a89d..2276957 100644 --- a/stacks/arraystack/arraystack.go +++ b/stacks/arraystack/arraystack.go @@ -32,13 +32,15 @@ package arraystack import ( "fmt" + "github.com/emirpasic/gods/containers" "github.com/emirpasic/gods/lists/arraylist" "github.com/emirpasic/gods/stacks" "strings" ) func assertInterfaceImplementation() { - var _ stacks.Interface = (*Stack)(nil) + var _ stacks.Stack = (*Stack)(nil) + var _ containers.IteratorWithIndex = (*Iterator)(nil) } type Stack struct { @@ -94,6 +96,37 @@ func (stack *Stack) Values() []interface{} { return elements } +type Iterator struct { + stack *Stack + index int +} + +// Returns a stateful iterator whose values can be fetched by an index. +func (stack *Stack) Iterator() Iterator { + return Iterator{stack: stack, index: -1} +} + +// Moves the iterator to the next element and returns true if there was a next element in the container. +// If Next() returns true, then next element's index and value can be retrieved by Index() and Value(). +// Modifies the state of the iterator. +func (iterator *Iterator) Next() bool { + iterator.index += 1 + return iterator.stack.withinRange(iterator.index) +} + +// Returns the current element's value. +// Does not modify the state of the iterator. +func (iterator *Iterator) Value() interface{} { + value, _ := iterator.stack.list.Get(iterator.stack.list.Size() - iterator.index - 1) // in reverse (LIFO) + return value +} + +// Returns the current element's index. +// Does not modify the state of the iterator. +func (iterator *Iterator) Index() int { + return iterator.index +} + func (stack *Stack) String() string { str := "ArrayStack\n" values := []string{} @@ -103,3 +136,8 @@ func (stack *Stack) String() string { str += strings.Join(values, ", ") return str } + +// Check that the index is withing bounds of the list +func (stack *Stack) withinRange(index int) bool { + return index >= 0 && index < stack.list.Size() +} diff --git a/stacks/arraystack/arraystack_test.go b/stacks/arraystack/arraystack_test.go index 62836db..65fed89 100644 --- a/stacks/arraystack/arraystack_test.go +++ b/stacks/arraystack/arraystack_test.go @@ -84,7 +84,41 @@ func TestArrayStack(t *testing.T) { if actualValue := stack.Values(); len(actualValue) != 0 { t.Errorf("Got %v expected %v", actualValue, "[]") } +} +func TestArrayStackIterator(t *testing.T) { + stack := New() + stack.Push("a") + stack.Push("b") + stack.Push("c") + + // Iterator + it := stack.Iterator() + for it.Next() { + index := it.Index() + value := it.Value() + switch index { + case 0: + if actualValue, expectedValue := value, "c"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + case 1: + if actualValue, expectedValue := value, "b"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + case 2: + if actualValue, expectedValue := value, "a"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + default: + t.Errorf("Too many") + } + } + stack.Clear() + it = stack.Iterator() + for it.Next() { + t.Errorf("Shouldn't iterate on empty stack") + } } func BenchmarkArrayStack(b *testing.B) { diff --git a/stacks/linkedliststack/linkedliststack.go b/stacks/linkedliststack/linkedliststack.go index bf96b4c..551377e 100644 --- a/stacks/linkedliststack/linkedliststack.go +++ b/stacks/linkedliststack/linkedliststack.go @@ -33,13 +33,15 @@ package linkedliststack import ( "fmt" + "github.com/emirpasic/gods/containers" "github.com/emirpasic/gods/lists/singlylinkedlist" "github.com/emirpasic/gods/stacks" "strings" ) func assertInterfaceImplementation() { - var _ stacks.Interface = (*Stack)(nil) + var _ stacks.Stack = (*Stack)(nil) + var _ containers.IteratorWithIndex = (*Iterator)(nil) } type Stack struct { @@ -90,6 +92,37 @@ func (stack *Stack) Values() []interface{} { return stack.list.Values() } +type Iterator struct { + stack *Stack + index int +} + +// Returns a stateful iterator whose values can be fetched by an index. +func (stack *Stack) Iterator() Iterator { + return Iterator{stack: stack, index: -1} +} + +// Moves the iterator to the next element and returns true if there was a next element in the container. +// If Next() returns true, then next element's index and value can be retrieved by Index() and Value(). +// Modifies the state of the iterator. +func (iterator *Iterator) Next() bool { + iterator.index += 1 + return iterator.stack.withinRange(iterator.index) +} + +// Returns the current element's value. +// Does not modify the state of the iterator. +func (iterator *Iterator) Value() interface{} { + value, _ := iterator.stack.list.Get(iterator.index) // in reverse (LIFO) + return value +} + +// Returns the current element's index. +// Does not modify the state of the iterator. +func (iterator *Iterator) Index() int { + return iterator.index +} + func (stack *Stack) String() string { str := "LinkedListStack\n" values := []string{} @@ -99,3 +132,8 @@ func (stack *Stack) String() string { str += strings.Join(values, ", ") return str } + +// Check that the index is withing bounds of the list +func (stack *Stack) withinRange(index int) bool { + return index >= 0 && index < stack.list.Size() +} diff --git a/stacks/linkedliststack/linkedliststack_test.go b/stacks/linkedliststack/linkedliststack_test.go index dea7ba0..2e082ff 100644 --- a/stacks/linkedliststack/linkedliststack_test.go +++ b/stacks/linkedliststack/linkedliststack_test.go @@ -84,7 +84,41 @@ func TestLinkedListStack(t *testing.T) { if actualValue := stack.Values(); len(actualValue) != 0 { t.Errorf("Got %v expected %v", actualValue, "[]") } +} +func TestLinkedListStackIterator(t *testing.T) { + stack := New() + stack.Push("a") + stack.Push("b") + stack.Push("c") + + // Iterator + it := stack.Iterator() + for it.Next() { + index := it.Index() + value := it.Value() + switch index { + case 0: + if actualValue, expectedValue := value, "c"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + case 1: + if actualValue, expectedValue := value, "b"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + case 2: + if actualValue, expectedValue := value, "a"; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + default: + t.Errorf("Too many") + } + } + stack.Clear() + it = stack.Iterator() + for it.Next() { + t.Errorf("Shouldn't iterate on empty stack") + } } func BenchmarkLinkedListStack(b *testing.B) { diff --git a/stacks/stacks.go b/stacks/stacks.go index fe9abbb..1f504be 100644 --- a/stacks/stacks.go +++ b/stacks/stacks.go @@ -28,12 +28,12 @@ package stacks import "github.com/emirpasic/gods/containers" -type Interface interface { +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() diff --git a/trees/binaryheap/binaryheap.go b/trees/binaryheap/binaryheap.go index 79f91b1..79e7ec5 100644 --- a/trees/binaryheap/binaryheap.go +++ b/trees/binaryheap/binaryheap.go @@ -33,6 +33,7 @@ package binaryheap import ( "fmt" + "github.com/emirpasic/gods/containers" "github.com/emirpasic/gods/lists/arraylist" "github.com/emirpasic/gods/trees" "github.com/emirpasic/gods/utils" @@ -40,7 +41,8 @@ import ( ) func assertInterfaceImplementation() { - var _ trees.Interface = (*Heap)(nil) + var _ trees.Tree = (*Heap)(nil) + var _ containers.IteratorWithIndex = (*Iterator)(nil) } type Heap struct { @@ -109,6 +111,37 @@ func (heap *Heap) Values() []interface{} { return heap.list.Values() } +type Iterator struct { + heap *Heap + index int +} + +// Returns a stateful iterator whose values can be fetched by an index. +func (heap *Heap) Iterator() Iterator { + return Iterator{heap: heap, index: -1} +} + +// Moves the iterator to the next element and returns true if there was a next element in the container. +// If Next() returns true, then next element's index and value can be retrieved by Index() and Value(). +// Modifies the state of the iterator. +func (iterator *Iterator) Next() bool { + iterator.index += 1 + return iterator.heap.withinRange(iterator.index) +} + +// Returns the current element's value. +// Does not modify the state of the iterator. +func (iterator *Iterator) Value() interface{} { + value, _ := iterator.heap.list.Get(iterator.index) + return value +} + +// Returns the current element's index. +// Does not modify the state of the iterator. +func (iterator *Iterator) Index() int { + return iterator.index +} + func (heap *Heap) String() string { str := "BinaryHeap\n" values := []string{} @@ -158,3 +191,8 @@ func (heap *Heap) bubbleUp() { index = parentIndex } } + +// Check that the index is withing bounds of the list +func (heap *Heap) withinRange(index int) bool { + return index >= 0 && index < heap.list.Size() +} diff --git a/trees/binaryheap/binaryheap_test.go b/trees/binaryheap/binaryheap_test.go index 473526f..66c80e1 100644 --- a/trees/binaryheap/binaryheap_test.go +++ b/trees/binaryheap/binaryheap_test.go @@ -103,7 +103,50 @@ func TestBinaryHeap(t *testing.T) { } prev = curr } +} + +func TestBinaryHeapIterator(t *testing.T) { + heap := NewWithIntComparator() + + if actualValue := heap.Empty(); actualValue != true { + t.Errorf("Got %v expected %v", actualValue, true) + } + + // insertions + heap.Push(3) + // [3] + heap.Push(2) + // [2,3] + heap.Push(1) + // [1,3,2](2 swapped with 1, hence last) + // Iterator + it := heap.Iterator() + for it.Next() { + index := it.Index() + value := it.Value() + switch index { + case 0: + if actualValue, expectedValue := value, 1; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + case 1: + if actualValue, expectedValue := value, 3; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + case 2: + if actualValue, expectedValue := value, 2; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + default: + t.Errorf("Too many") + } + } + heap.Clear() + it = heap.Iterator() + for it.Next() { + t.Errorf("Shouldn't iterate on empty stack") + } } func BenchmarkBinaryHeap(b *testing.B) { diff --git a/trees/redblacktree/redblacktree.go b/trees/redblacktree/redblacktree.go index 2fe165b..c6a033e 100644 --- a/trees/redblacktree/redblacktree.go +++ b/trees/redblacktree/redblacktree.go @@ -33,13 +33,15 @@ package redblacktree import ( "fmt" + "github.com/emirpasic/gods/containers" "github.com/emirpasic/gods/stacks/linkedliststack" "github.com/emirpasic/gods/trees" "github.com/emirpasic/gods/utils" ) func assertInterfaceImplementation() { - var _ trees.Interface = (*Tree)(nil) + var _ trees.Tree = (*Tree)(nil) + var _ containers.IteratorWithKey = (*Iterator)(nil) } type color bool @@ -272,6 +274,55 @@ func (tree *Tree) Clear() { tree.size = 0 } +type Iterator struct { + tree *Tree + left *Node +} + +// Returns a stateful iterator whose elements are key/value pairs. +func (tree *Tree) Iterator() Iterator { + return Iterator{tree: tree, left: nil} +} + +// Moves the iterator to the next element and returns true if there was a next element in the container. +// If Next() returns true, then next element's key and value can be retrieved by Key() and Value(). +// Modifies the state of the iterator. +func (iterator *Iterator) Next() bool { + if iterator.left == nil { + iterator.left = iterator.tree.Left() + return iterator.left != nil + } + if iterator.left.Right != nil { + iterator.left = iterator.left.Right + for iterator.left.Left != nil { + iterator.left = iterator.left.Left + } + return true + } + if iterator.left.Parent != nil { + key := iterator.left.Key + for iterator.left.Parent != nil { + iterator.left = iterator.left.Parent + if iterator.tree.Comparator(key, iterator.left.Key) <= 0 { + return true + } + } + } + return false +} + +// Returns the current element's value. +// Does not modify the state of the iterator. +func (iterator *Iterator) Value() interface{} { + return iterator.left.Value +} + +// Returns the current element's key. +// Does not modify the state of the iterator. +func (iterator *Iterator) Key() interface{} { + return iterator.left.Key +} + func (tree *Tree) String() string { str := "RedBlackTree\n" if !tree.Empty() { diff --git a/trees/redblacktree/redblacktree_test.go b/trees/redblacktree/redblacktree_test.go index 20a287c..eee8955 100644 --- a/trees/redblacktree/redblacktree_test.go +++ b/trees/redblacktree/redblacktree_test.go @@ -216,6 +216,128 @@ func TestRedBlackTree(t *testing.T) { } } +func TestRedBlackTreeIterator(t *testing.T) { + tree := NewWithIntComparator() + + // insertions + tree.Put(5, "e") + tree.Put(6, "f") + tree.Put(7, "g") + tree.Put(3, "c") + tree.Put(4, "d") + tree.Put(1, "x") + tree.Put(2, "b") + tree.Put(1, "a") //overwrite + + // Iterator + it := tree.Iterator() + count := 0 + for it.Next() { + count += 1 + index := it.Key() + switch index { + case count: + if actualValue, expectedValue := index, count; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + default: + if actualValue, expectedValue := index, count; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + } + } + if actualValue, expectedValue := count, 7; actualValue != expectedValue { + t.Errorf("Size different. Got %v expected %v", actualValue, expectedValue) + } + + // Iterator + tree.Clear() + tree.Put(3, "c") + tree.Put(1, "a") + tree.Put(2, "b") + it = tree.Iterator() + count = 0 + for it.Next() { + count += 1 + index := it.Key() + switch index { + case count: + if actualValue, expectedValue := index, count; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + default: + if actualValue, expectedValue := index, count; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + } + } + if actualValue, expectedValue := count, 3; actualValue != expectedValue { + t.Errorf("Size different. Got %v expected %v", actualValue, expectedValue) + } + + // Iterator + tree.Clear() + tree.Put(1, "a") + it = tree.Iterator() + count = 0 + for it.Next() { + count += 1 + index := it.Key() + switch index { + case count: + if actualValue, expectedValue := index, count; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + default: + if actualValue, expectedValue := index, count; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + } + } + if actualValue, expectedValue := count, 1; actualValue != expectedValue { + t.Errorf("Size different. Got %v expected %v", actualValue, expectedValue) + } + + // Iterator on empty + tree.Clear() + it = tree.Iterator() + for it.Next() { + t.Errorf("Shouldn't iterate on empty stack") + } + + // Iterator (from image) + tree.Clear() + tree.Put(13, 5) + tree.Put(8, 3) + tree.Put(17, 7) + tree.Put(1, 1) + tree.Put(11, 4) + tree.Put(15, 6) + tree.Put(25, 9) + tree.Put(6, 2) + tree.Put(22, 8) + tree.Put(27, 10) + it = tree.Iterator() + count = 0 + for it.Next() { + count += 1 + value := it.Value() + switch value { + case count: + if actualValue, expectedValue := value, count; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + default: + if actualValue, expectedValue := value, count; actualValue != expectedValue { + t.Errorf("Got %v expected %v", actualValue, expectedValue) + } + } + } + if actualValue, expectedValue := count, 10; actualValue != expectedValue { + t.Errorf("Size different. Got %v expected %v", actualValue, expectedValue) + } +} + func BenchmarkRedBlackTree(b *testing.B) { for i := 0; i < b.N; i++ { tree := NewWithIntComparator() diff --git a/trees/trees.go b/trees/trees.go index 3714bee..0a021dd 100644 --- a/trees/trees.go +++ b/trees/trees.go @@ -28,8 +28,8 @@ package trees import "github.com/emirpasic/gods/containers" -type Interface interface { - containers.Interface +type Tree interface { + containers.Container // Empty() bool // Size() int // Clear()