pull/15/head
Emir Pasic 8 years ago
parent 35457aba81
commit ef9baa808a

@ -24,12 +24,11 @@ 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.
*/
// All data structures must implement the container structure
package containers
import "github.com/emirpasic/gods/utils"
// Container is base interface that all data structures implement
type Container interface {
Empty() bool
Size() int
@ -37,7 +36,7 @@ type Container interface {
Values() []interface{}
}
// Returns sorted container's elements with respect to the passed comparator.
// GetSortedValues 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{} {

@ -29,57 +29,57 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package containers
// Enumerable functions for ordered containers whose values can be fetched by an index.
// EnumerableWithIndex provides 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 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
// Map 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.
// Select 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
// Any 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
// All 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
// 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.
Find(func(index int, value interface{}) bool) (int, interface{})
}
// Enumerable functions for ordered containers whose values whose elements are key/value pairs.
// EnumerableWithKey provides 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 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
// 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.
// 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.
// Select 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
// Any 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
// All 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
// 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.
Find(func(key interface{}, value interface{}) bool) (interface{}, interface{})

@ -28,30 +28,30 @@ OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
package containers
// Stateful iterator for ordered containers whose values can be fetched by an index.
// IteratorWithIndex is 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.
// Next 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.
// Value returns the current element's value.
// Does not modify the state of the iterator.
Value() interface{}
// Returns the current element's index.
// Index 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.
// IteratorWithKey is a 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.
// Next 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.
// Value returns the current element's value.
// Does not modify the state of the iterator.
Value() interface{}
// Returns the current element's key.
// Key returns the current element's key.
// Does not modify the state of the iterator.
Key() interface{}
}

@ -31,6 +31,7 @@ import (
"github.com/emirpasic/gods/utils"
)
// ArrayListExample to demonstrate basic usage of ArrayList
func ArrayListExample() {
list := arraylist.New()
list.Add("a") // ["a"]

@ -28,6 +28,7 @@ package examples
import "github.com/emirpasic/gods/stacks/arraystack"
// ArrayStackExample to demonstrate basic usage of ArrayStack
func ArrayStackExample() {
stack := arraystack.New() // empty
stack.Push(1) // 1

@ -31,6 +31,7 @@ import (
"github.com/emirpasic/gods/utils"
)
// BinaryHeapExample to demonstrate basic usage of BinaryHeap
func BinaryHeapExample() {
// Min-heap

@ -31,6 +31,7 @@ import (
"github.com/emirpasic/gods/sets/treeset"
)
// User model (id and name)
type User struct {
id int
name string
@ -53,6 +54,7 @@ func byID(a, b interface{}) int {
}
}
// CustomComparatorExample to demonstrate basic usage of CustomComparator
func CustomComparatorExample() {
set := treeset.NewWith(byID)

@ -31,6 +31,7 @@ import (
"github.com/emirpasic/gods/utils"
)
// DoublyLinkedListExample to demonstrate basic usage of DoublyLinkedList
func DoublyLinkedListExample() {
list := dll.New()
list.Add("a") // ["a"]

@ -39,7 +39,8 @@ func printSet(txt string, set *treeset.Set) {
fmt.Println("]")
}
func EnumerableWithIndexTest() {
// EnumerableWithIndexExample to demonstrate basic usage of EnumerableWithIndex
func EnumerableWithIndexExample() {
set := treeset.NewWithIntComparator()
set.Add(2, 3, 4, 2, 5, 6, 7, 8)
printSet("Initial", set) // [ 2 3 4 5 6 7 8 ]

@ -39,7 +39,8 @@ func printMap(txt string, m *treemap.Map) {
fmt.Println("}")
}
func EunumerableWithKey() {
// EunumerableWithKeyExample to demonstrate basic usage of EunumerableWithKey
func EunumerableWithKeyExample() {
m := treemap.NewWithStringComparator()
m.Put("g", 7)
m.Put("f", 6)

@ -28,6 +28,7 @@ package examples
import "github.com/emirpasic/gods/maps/hashmap"
// HashMapExample to demonstrate basic usage of HashMap
func HashMapExample() {
m := hashmap.New() // empty
m.Put(1, "x") // 1->x

@ -28,6 +28,7 @@ package examples
import "github.com/emirpasic/gods/sets/hashset"
// HashSetExample to demonstrate basic usage of HashSet
func HashSetExample() {
set := hashset.New() // empty (keys are of type int)
set.Add(1) // 1

@ -28,6 +28,7 @@ package examples
import lls "github.com/emirpasic/gods/stacks/linkedliststack"
// LinkedListStackExample to demonstrate basic usage of LinkedListStack
func LinkedListStackExample() {
stack := lls.New() // empty
stack.Push(1) // 1

@ -31,6 +31,7 @@ import (
rbt "github.com/emirpasic/gods/trees/redblacktree"
)
// RedBlackTreeExample to demonstrate basic usage of RedBlackTree
func RedBlackTreeExample() {
tree := rbt.NewWithIntComparator() // empty(keys are of type int)

@ -31,46 +31,47 @@ import (
rbt "github.com/emirpasic/gods/trees/redblacktree"
)
// RedBlackTreeExtended to demonstrate how to extend a RedBlackTree to include new functions
type RedBlackTreeExtended struct {
*rbt.Tree
}
// GetMin gets the min value and flag if found
func (tree *RedBlackTreeExtended) GetMin() (value interface{}, found bool) {
node, found := tree.getMinFromNode(tree.Root)
if node != nil {
return node.Value, found
} else {
return nil, false
}
return nil, false
}
// GetMax gets the max value and flag if found
func (tree *RedBlackTreeExtended) GetMax() (value interface{}, found bool) {
node, found := tree.getMaxFromNode(tree.Root)
if node != nil {
return node.Value, found
} else {
return nil, false
}
return nil, false
}
// RemoveMin removes the min value and flag if found
func (tree *RedBlackTreeExtended) RemoveMin() (value interface{}, deleted bool) {
node, found := tree.getMinFromNode(tree.Root)
if found {
tree.Remove(node.Key)
return node.Value, found
} else {
return nil, false
}
return nil, false
}
// RemoveMax removes the max value and flag if found
func (tree *RedBlackTreeExtended) RemoveMax() (value interface{}, deleted bool) {
node, found := tree.getMaxFromNode(tree.Root)
if found {
tree.Remove(node.Key)
return node.Value, found
} else {
return nil, false
}
return nil, false
}
func (tree *RedBlackTreeExtended) getMinFromNode(node *rbt.Node) (foundNode *rbt.Node, found bool) {
@ -79,9 +80,8 @@ func (tree *RedBlackTreeExtended) getMinFromNode(node *rbt.Node) (foundNode *rbt
}
if node.Left == nil {
return node, true
} else {
return tree.getMinFromNode(node.Left)
}
return tree.getMinFromNode(node.Left)
}
func (tree *RedBlackTreeExtended) getMaxFromNode(node *rbt.Node) (foundNode *rbt.Node, found bool) {
@ -90,9 +90,8 @@ func (tree *RedBlackTreeExtended) getMaxFromNode(node *rbt.Node) (foundNode *rbt
}
if node.Right == nil {
return node, true
} else {
return tree.getMaxFromNode(node.Right)
}
return tree.getMaxFromNode(node.Right)
}
func print(tree *RedBlackTreeExtended) {
@ -103,6 +102,7 @@ func print(tree *RedBlackTreeExtended) {
fmt.Println(tree)
}
// RedBlackTreeExtendedExample main method on how to use the custom red-black tree above
func RedBlackTreeExtendedExample() {
tree := RedBlackTreeExtended{rbt.NewWithIntComparator()}

@ -31,6 +31,7 @@ import (
"github.com/emirpasic/gods/utils"
)
// SinglyLinkedListExample to demonstrate basic usage of SinglyLinkedList
func SinglyLinkedListExample() {
list := sll.New()
list.Add("a") // ["a"]

@ -28,6 +28,7 @@ package examples
import "github.com/emirpasic/gods/utils"
// SortExample to demonstrate basic usage of basic sort (timsort)
func SortExample() {
strings := []interface{}{} // []
strings = append(strings, "d") // ["d"]

@ -28,6 +28,7 @@ package examples
import "github.com/emirpasic/gods/maps/treemap"
// TreeMapExample to demonstrate basic usage of TreeMap
func TreeMapExample() {
m := treemap.NewWithIntComparator() // empty (keys are of type int)
m.Put(1, "x") // 1->x

@ -28,6 +28,7 @@ package examples
import "github.com/emirpasic/gods/sets/treeset"
// TreeSetExample to demonstrate basic usage of TreeSet
func TreeSetExample() {
set := treeset.NewWithIntComparator() // empty
set.Add(1) // 1

@ -44,31 +44,32 @@ func assertInterfaceImplementation() {
var _ containers.IteratorWithIndex = (*Iterator)(nil)
}
// List holds the elements in a slice
type List struct {
elements []interface{}
size int
}
const (
GROWTH_FACTOR = float32(2.0) // growth by 100%
SHRINK_FACTOR = float32(0.25) // shrink when size is 25% of capacity (0 means never shrink)
growthFactor = float32(2.0) // growth by 100%
shrinkFactor = float32(0.25) // shrink when size is 25% of capacity (0 means never shrink)
)
// Instantiates a new empty list
// New instantiates a new empty list
func New() *List {
return &List{}
}
// Appends a value at the end of the list
// Add appends a value at the end of the list
func (list *List) Add(values ...interface{}) {
list.growBy(len(values))
for _, value := range values {
list.elements[list.size] = value
list.size += 1
list.size++
}
}
// Returns the element at index.
// Get returns the element at index.
// Second return parameter is true if index is within bounds of the array and array is not empty, otherwise false.
func (list *List) Get(index int) (interface{}, bool) {
@ -79,7 +80,7 @@ func (list *List) Get(index int) (interface{}, bool) {
return list.elements[index], true
}
// Removes one or more elements from the list with the supplied indices.
// Remove removes one or more elements from the list with the supplied indices.
func (list *List) Remove(index int) {
if !list.withinRange(index) {
@ -88,12 +89,12 @@ func (list *List) Remove(index int) {
list.elements[index] = nil // cleanup reference
copy(list.elements[index:], list.elements[index+1:list.size]) // shift to the left by one (slow operation, need ways to optimize this)
list.size -= 1
list.size--
list.shrink()
}
// Check if elements (one or more) are present in the set.
// Contains checks if elements (one or more) are present in the set.
// All elements have to be present in the set for the method to return true.
// Performance time complexity of n^2.
// Returns true if no arguments are passed at all, i.e. set is always super-set of empty set.
@ -114,30 +115,30 @@ func (list *List) Contains(values ...interface{}) bool {
return true
}
// Returns all elements in the list.
// Values returns all elements in the list.
func (list *List) Values() []interface{} {
newElements := make([]interface{}, list.size, list.size)
copy(newElements, list.elements[:list.size])
return newElements
}
// Returns true if list does not contain any elements.
// Empty returns true if list does not contain any elements.
func (list *List) Empty() bool {
return list.size == 0
}
// Returns number of elements within the list.
// Size returns number of elements within the list.
func (list *List) Size() int {
return list.size
}
// Removes all elements from the list.
// Clear removes all elements from the list.
func (list *List) Clear() {
list.size = 0
list.elements = []interface{}{}
}
// Sorts values (in-place) using timsort.
// Sort sorts values (in-place) using timsort.
func (list *List) Sort(comparator utils.Comparator) {
if len(list.elements) < 2 {
return
@ -145,14 +146,14 @@ func (list *List) Sort(comparator utils.Comparator) {
utils.Sort(list.elements[:list.size], comparator)
}
// Swaps the two values at the specified positions.
// Swap swaps the two values at the specified positions.
func (list *List) Swap(i, j int) {
if list.withinRange(i) && list.withinRange(j) {
list.elements[i], list.elements[j] = list.elements[j], list.elements[i]
}
}
// Inserts values at specified index position shifting the value at that position (if any) and any subsequent elements to the right.
// Insert inserts values at specified index position shifting the value at that position (if any) and any subsequent elements to the right.
// Does not do anything if position is negative or bigger than list's size
// Note: position equal to list's size is valid, i.e. append.
func (list *List) Insert(index int, values ...interface{}) {
@ -178,37 +179,38 @@ func (list *List) Insert(index int, values ...interface{}) {
}
}
// Iterator holding the iterator's state
type Iterator struct {
list *List
index int
}
// Returns a stateful iterator whose values can be fetched by an index.
// Iterator 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.
// Next 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
iterator.index++
return iterator.list.withinRange(iterator.index)
}
// Returns the current element's value.
// Value 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.
// 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.
// Each 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() {
@ -216,7 +218,7 @@ func (list *List) Each(f func(index int, value interface{})) {
}
}
// Invokes the given function once for each element and returns a
// Map 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{}
@ -227,7 +229,7 @@ func (list *List) Map(f func(index int, value interface{}) interface{}) *List {
return newList
}
// Returns a new container containing all elements for which the given function returns a true value.
// Select 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()
@ -239,7 +241,7 @@ func (list *List) Select(f func(index int, value interface{}) bool) *List {
return newList
}
// Passes each element of the collection to the given function and
// Any 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()
@ -251,7 +253,7 @@ func (list *List) Any(f func(index int, value interface{}) bool) bool {
return false
}
// Passes each element of the collection to the given function and
// All 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()
@ -263,7 +265,7 @@ func (list *List) All(f func(index int, value interface{}) bool) bool {
return true
}
// Passes each element of the container to the given function and returns
// 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.
func (list *List) Find(f func(index int, value interface{}) bool) (int, interface{}) {
@ -276,6 +278,7 @@ func (list *List) Find(f func(index int, value interface{}) bool) (int, interfac
return -1, nil
}
// String returns a string representation of container
func (list *List) String() string {
str := "ArrayList\n"
values := []string{}
@ -299,22 +302,22 @@ func (list *List) resize(cap int) {
// Expand the array if necessary, i.e. capacity will be reached if we add n elements
func (list *List) growBy(n int) {
// When capacity is reached, grow by a factor of GROWTH_FACTOR and add number of elements
// When capacity is reached, grow by a factor of growthFactor and add number of elements
currentCapacity := cap(list.elements)
if list.size+n >= currentCapacity {
newCapacity := int(GROWTH_FACTOR * float32(currentCapacity+n))
newCapacity := int(growthFactor * float32(currentCapacity+n))
list.resize(newCapacity)
}
}
// Shrink the array if necessary, i.e. when size is SHRINK_FACTOR percent of current capacity
// Shrink the array if necessary, i.e. when size is shrinkFactor percent of current capacity
func (list *List) shrink() {
if SHRINK_FACTOR == 0.0 {
if shrinkFactor == 0.0 {
return
}
// Shrink when size is at SHRINK_FACTOR * capacity
// Shrink when size is at shrinkFactor * capacity
currentCapacity := cap(list.elements)
if list.size <= int(float32(currentCapacity)*SHRINK_FACTOR) {
if list.size <= int(float32(currentCapacity)*shrinkFactor) {
list.resize(list.size)
}
}

@ -44,6 +44,7 @@ func assertInterfaceImplementation() {
var _ containers.IteratorWithIndex = (*Iterator)(nil)
}
// List holds the elements, where each element points to the next and previous element
type List struct {
first *element
last *element
@ -56,12 +57,12 @@ type element struct {
next *element
}
// Instantiates a new empty list
// New instantiates a new empty list
func New() *List {
return &List{}
}
// Appends a value (one or more) at the end of the list (same as Append())
// Add appends a value (one or more) at the end of the list (same as Append())
func (list *List) Add(values ...interface{}) {
for _, value := range values {
newElement := &element{value: value, prev: list.last}
@ -76,12 +77,12 @@ func (list *List) Add(values ...interface{}) {
}
}
// Appends a value (one or more) at the end of the list (same as Add())
// Append appends a value (one or more) at the end of the list (same as Add())
func (list *List) Append(values ...interface{}) {
list.Add(values...)
}
// Prepends a values (or more)
// Prepend prepends a values (or more)
func (list *List) Prepend(values ...interface{}) {
// in reverse to keep passed order i.e. ["c","d"] -> Prepend(["a","b"]) -> ["a","b","c",d"]
for v := len(values) - 1; v >= 0; v-- {
@ -97,7 +98,7 @@ func (list *List) Prepend(values ...interface{}) {
}
}
// Returns the element at index.
// Get returns the element at index.
// Second return parameter is true if index is within bounds of the array and array is not empty, otherwise false.
func (list *List) Get(index int) (interface{}, bool) {
@ -111,16 +112,14 @@ func (list *List) Get(index int) (interface{}, bool) {
for e := list.size - 1; e != index; e, element = e-1, element.prev {
}
return element.value, true
} else {
element := list.first
for e := 0; e != index; e, element = e+1, element.next {
}
return element.value, true
}
element := list.first
for e := 0; e != index; e, element = e+1, element.next {
}
return element.value, true
}
// Removes one or more elements from the list with the supplied indices.
// Remove removes one or more elements from the list with the supplied indices.
func (list *List) Remove(index int) {
if !list.withinRange(index) {
@ -162,7 +161,7 @@ func (list *List) Remove(index int) {
list.size--
}
// Check if values (one or more) are present in the set.
// Contains check if values (one or more) are present in the set.
// All values have to be present in the set for the method to return true.
// Performance time complexity of n^2.
// Returns true if no arguments are passed at all, i.e. set is always super-set of empty set.
@ -189,7 +188,7 @@ func (list *List) Contains(values ...interface{}) bool {
return true
}
// Returns all elements in the list.
// Values returns all elements in the list.
func (list *List) Values() []interface{} {
values := make([]interface{}, list.size, list.size)
for e, element := 0, list.first; element != nil; e, element = e+1, element.next {
@ -198,24 +197,24 @@ func (list *List) Values() []interface{} {
return values
}
// Returns true if list does not contain any elements.
// Empty returns true if list does not contain any elements.
func (list *List) Empty() bool {
return list.size == 0
}
// Returns number of elements within the list.
// Size returns number of elements within the list.
func (list *List) Size() int {
return list.size
}
// Removes all elements from the list.
// Clear removes all elements from the list.
func (list *List) Clear() {
list.size = 0
list.first = nil
list.last = nil
}
// Sorts values (in-place) using timsort.
// Sort sorts values (in-place) using timsort.
func (list *List) Sort(comparator utils.Comparator) {
if list.size < 2 {
@ -231,7 +230,7 @@ func (list *List) Sort(comparator utils.Comparator) {
}
// Swaps values of two elements at the given indices.
// Swap swaps values of two elements at the given indices.
func (list *List) Swap(i, j int) {
if list.withinRange(i) && list.withinRange(j) && i != j {
var element1, element2 *element
@ -247,7 +246,7 @@ func (list *List) Swap(i, j int) {
}
}
// Inserts values at specified index position shifting the value at that position (if any) and any subsequent elements to the right.
// Insert inserts values at specified index position shifting the value at that position (if any) and any subsequent elements to the right.
// Does not do anything if position is negative or bigger than list's size
// Note: position equal to list's size is valid, i.e. append.
func (list *List) Insert(index int, values ...interface{}) {
@ -300,22 +299,23 @@ func (list *List) Insert(index int, values ...interface{}) {
}
}
// Iterator holding the iterator's state
type Iterator struct {
list *List
index int
element *element
}
// Returns a stateful iterator whose values can be fetched by an index.
// Iterator 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.
// Next 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
iterator.index++
if !iterator.list.withinRange(iterator.index) {
iterator.element = nil
return false
@ -328,19 +328,19 @@ func (iterator *Iterator) Next() bool {
return true
}
// Returns the current element's value.
// Value 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.
// 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.
// Each 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() {
@ -348,7 +348,7 @@ func (list *List) Each(f func(index int, value interface{})) {
}
}
// Invokes the given function once for each element and returns a
// Map 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{}
@ -359,7 +359,7 @@ func (list *List) Map(f func(index int, value interface{}) interface{}) *List {
return newList
}
// Returns a new container containing all elements for which the given function returns a true value.
// Select 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()
@ -371,7 +371,7 @@ func (list *List) Select(f func(index int, value interface{}) bool) *List {
return newList
}
// Passes each element of the container to the given function and
// Any 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()
@ -383,7 +383,7 @@ func (list *List) Any(f func(index int, value interface{}) bool) bool {
return false
}
// Passes each element of the container to the given function and
// All 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()
@ -395,7 +395,7 @@ func (list *List) All(f func(index int, value interface{}) bool) bool {
return true
}
// Passes each element of the container to the given function and returns
// 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.
func (list *List) Find(f func(index int, value interface{}) bool) (index int, value interface{}) {
@ -408,6 +408,7 @@ func (list *List) Find(f func(index int, value interface{}) bool) (index int, va
return -1, nil
}
// String returns a string representation of container
func (list *List) String() string {
str := "DoublyLinkedList\n"
values := []string{}

@ -23,6 +23,7 @@ import (
"github.com/emirpasic/gods/utils"
)
// List interface that all lists implement
type List interface {
Get(index int) (interface{}, bool)
Remove(index int)

@ -44,6 +44,7 @@ func assertInterfaceImplementation() {
var _ containers.IteratorWithIndex = (*Iterator)(nil)
}
// List holds the elements, where each element points to the next element
type List struct {
first *element
last *element
@ -55,12 +56,12 @@ type element struct {
next *element
}
// Instantiates a new empty list
// New instantiates a new empty list
func New() *List {
return &List{}
}
// Appends a value (one or more) at the end of the list (same as Append())
// Add appends a value (one or more) at the end of the list (same as Append())
func (list *List) Add(values ...interface{}) {
for _, value := range values {
newElement := &element{value: value}
@ -75,12 +76,12 @@ func (list *List) Add(values ...interface{}) {
}
}
// Appends a value (one or more) at the end of the list (same as Add())
// Append appends a value (one or more) at the end of the list (same as Add())
func (list *List) Append(values ...interface{}) {
list.Add(values...)
}
// Prepends a values (or more)
// Prepend prepends a values (or more)
func (list *List) Prepend(values ...interface{}) {
// in reverse to keep passed order i.e. ["c","d"] -> Prepend(["a","b"]) -> ["a","b","c",d"]
for v := len(values) - 1; v >= 0; v-- {
@ -93,7 +94,7 @@ func (list *List) Prepend(values ...interface{}) {
}
}
// Returns the element at index.
// Get returns the element at index.
// Second return parameter is true if index is within bounds of the array and array is not empty, otherwise false.
func (list *List) Get(index int) (interface{}, bool) {
@ -108,7 +109,7 @@ func (list *List) Get(index int) (interface{}, bool) {
return element.value, true
}
// Removes one or more elements from the list with the supplied indices.
// Remove removes one or more elements from the list with the supplied indices.
func (list *List) Remove(index int) {
if !list.withinRange(index) {
@ -141,7 +142,7 @@ func (list *List) Remove(index int) {
list.size--
}
// Check if values (one or more) are present in the set.
// Contains checks if values (one or more) are present in the set.
// All values have to be present in the set for the method to return true.
// Performance time complexity of n^2.
// Returns true if no arguments are passed at all, i.e. set is always super-set of empty set.
@ -168,7 +169,7 @@ func (list *List) Contains(values ...interface{}) bool {
return true
}
// Returns all elements in the list.
// Values returns all elements in the list.
func (list *List) Values() []interface{} {
values := make([]interface{}, list.size, list.size)
for e, element := 0, list.first; element != nil; e, element = e+1, element.next {
@ -177,24 +178,24 @@ func (list *List) Values() []interface{} {
return values
}
// Returns true if list does not contain any elements.
// Empty returns true if list does not contain any elements.
func (list *List) Empty() bool {
return list.size == 0
}
// Returns number of elements within the list.
// Size returns number of elements within the list.
func (list *List) Size() int {
return list.size
}
// Removes all elements from the list.
// Clear removes all elements from the list.
func (list *List) Clear() {
list.size = 0
list.first = nil
list.last = nil
}
// Sorts values (in-place) using timsort.
// Sort sort values (in-place) using timsort.
func (list *List) Sort(comparator utils.Comparator) {
if list.size < 2 {
@ -210,7 +211,7 @@ func (list *List) Sort(comparator utils.Comparator) {
}
// Swaps values of two elements at the given indices.
// Swap swaps values of two elements at the given indices.
func (list *List) Swap(i, j int) {
if list.withinRange(i) && list.withinRange(j) && i != j {
var element1, element2 *element
@ -226,7 +227,7 @@ func (list *List) Swap(i, j int) {
}
}
// Inserts values at specified index position shifting the value at that position (if any) and any subsequent elements to the right.
// Insert inserts values at specified index position shifting the value at that position (if any) and any subsequent elements to the right.
// Does not do anything if position is negative or bigger than list's size
// Note: position equal to list's size is valid, i.e. append.
func (list *List) Insert(index int, values ...interface{}) {
@ -270,22 +271,23 @@ func (list *List) Insert(index int, values ...interface{}) {
}
}
// Iterator holding the iterator's state
type Iterator struct {
list *List
index int
element *element
}
// Returns a stateful iterator whose values can be fetched by an index.
// Iterator 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.
// Next 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
iterator.index++
if !iterator.list.withinRange(iterator.index) {
iterator.element = nil
return false
@ -298,19 +300,19 @@ func (iterator *Iterator) Next() bool {
return true
}
// Returns the current element's value.
// Value 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.
// 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.
// Each 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() {
@ -318,7 +320,7 @@ func (list *List) Each(f func(index int, value interface{})) {
}
}
// Invokes the given function once for each element and returns a
// Map 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{}
@ -329,7 +331,7 @@ func (list *List) Map(f func(index int, value interface{}) interface{}) *List {
return newList
}
// Returns a new container containing all elements for which the given function returns a true value.
// Select 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()
@ -341,7 +343,7 @@ func (list *List) Select(f func(index int, value interface{}) bool) *List {
return newList
}
// Passes each element of the container to the given function and
// Any 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()
@ -353,7 +355,7 @@ func (list *List) Any(f func(index int, value interface{}) bool) bool {
return false
}
// Passes each element of the container to the given function and
// All 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()
@ -365,7 +367,7 @@ func (list *List) All(f func(index int, value interface{}) bool) bool {
return true
}
// Passes each element of the container to the given function and returns
// 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.
func (list *List) Find(f func(index int, value interface{}) bool) (index int, value interface{}) {
@ -378,6 +380,7 @@ func (list *List) Find(f func(index int, value interface{}) bool) (index int, va
return -1, nil
}
// String returns a string representation of container
func (list *List) String() string {
str := "SinglyLinkedList\n"
values := []string{}

@ -40,69 +40,71 @@ func assertInterfaceImplementation() {
var _ maps.Map = (*Map)(nil)
}
// Map holds the elements in go's native map
type Map struct {
m map[interface{}]interface{}
}
// Instantiates a hash map.
// New instantiates a hash map.
func New() *Map {
return &Map{m: make(map[interface{}]interface{})}
}
// Inserts element into the map.
// Put inserts element into the map.
func (m *Map) Put(key interface{}, value interface{}) {
m.m[key] = value
}
// Searches the elemnt in the map by key and returns its value or nil if key is not found in map.
// Get searches the elemnt in the map by key and returns its value or nil if key is not found in map.
// Second return parameter is true if key was found, otherwise false.
func (m *Map) Get(key interface{}) (value interface{}, found bool) {
value, found = m.m[key]
return
}
// Remove the element from the map by key.
// Remove removes the element from the map by key.
func (m *Map) Remove(key interface{}) {
delete(m.m, key)
}
// Returns true if map does not contain any elements
// Empty returns true if map does not contain any elements
func (m *Map) Empty() bool {
return m.Size() == 0
}
// Returns number of elements in the map.
// Size returns number of elements in the map.
func (m *Map) Size() int {
return len(m.m)
}
// Returns all keys (random order).
// Keys returns all keys (random order).
func (m *Map) Keys() []interface{} {
keys := make([]interface{}, m.Size())
count := 0
for key := range m.m {
keys[count] = key
count += 1
count++
}
return keys
}
// Returns all values (random order).
// Values returns all values (random order).
func (m *Map) Values() []interface{} {
values := make([]interface{}, m.Size())
count := 0
for _, value := range m.m {
values[count] = value
count += 1
count++
}
return values
}
// Removes all elements from the map.
// Clear removes all elements from the map.
func (m *Map) Clear() {
m.m = make(map[interface{}]interface{})
}
// String returns a string representation of container
func (m *Map) String() string {
str := "HashMap\n"
str += fmt.Sprintf("%v", m.m)

@ -28,6 +28,7 @@ package maps
import "github.com/emirpasic/gods/containers"
// Map interface that all maps implement
type Map interface {
Put(key interface{}, value interface{})
Get(key interface{}) (value interface{}, found bool)

@ -44,70 +44,71 @@ func assertInterfaceImplementation() {
var _ containers.IteratorWithKey = (*Iterator)(nil)
}
// Map holds the elements in a red-black tree
type Map struct {
tree *rbt.Tree
}
// Instantiates a tree map with the custom comparator.
// NewWith instantiates a tree map with the custom comparator.
func NewWith(comparator utils.Comparator) *Map {
return &Map{tree: rbt.NewWith(comparator)}
}
// Instantiates a tree map with the IntComparator, i.e. keys are of type int.
// NewWithIntComparator instantiates a tree map with the IntComparator, i.e. keys are of type int.
func NewWithIntComparator() *Map {
return &Map{tree: rbt.NewWithIntComparator()}
}
// Instantiates a tree map with the StringComparator, i.e. keys are of type string.
// NewWithStringComparator instantiates a tree map with the StringComparator, i.e. keys are of type string.
func NewWithStringComparator() *Map {
return &Map{tree: rbt.NewWithStringComparator()}
}
// Inserts key-value pair into the map.
// Put inserts key-value pair into the map.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (m *Map) Put(key interface{}, value interface{}) {
m.tree.Put(key, value)
}
// Searches the element in the map by key and returns its value or nil if key is not found in tree.
// Get searches the element in the map by key and returns its value or nil if key is not found in tree.
// Second return parameter is true if key was found, otherwise false.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (m *Map) Get(key interface{}) (value interface{}, found bool) {
return m.tree.Get(key)
}
// Remove the element from the map by key.
// Remove removes the element from the map by key.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (m *Map) Remove(key interface{}) {
m.tree.Remove(key)
}
// Returns true if map does not contain any elements
// Empty returns true if map does not contain any elements
func (m *Map) Empty() bool {
return m.tree.Empty()
}
// Returns number of elements in the map.
// Size returns number of elements in the map.
func (m *Map) Size() int {
return m.tree.Size()
}
// Returns all keys in-order
// Keys returns all keys in-order
func (m *Map) Keys() []interface{} {
return m.tree.Keys()
}
// Returns all values in-order based on the key.
// Values returns all values in-order based on the key.
func (m *Map) Values() []interface{} {
return m.tree.Values()
}
// Removes all elements from the map.
// Clear removes all elements from the map.
func (m *Map) Clear() {
m.tree.Clear()
}
// Returns the minimum key and its value from the tree map.
// Min returns the minimum key and its value from the tree map.
// Returns nil, nil if map is empty.
func (m *Map) Min() (key interface{}, value interface{}) {
if node := m.tree.Left(); node != nil {
@ -116,7 +117,7 @@ func (m *Map) Min() (key interface{}, value interface{}) {
return nil, nil
}
// Returns the maximum key and its value from the tree map.
// Max returns the maximum key and its value from the tree map.
// Returns nil, nil if map is empty.
func (m *Map) Max() (key interface{}, value interface{}) {
if node := m.tree.Right(); node != nil {
@ -125,35 +126,36 @@ func (m *Map) Max() (key interface{}, value interface{}) {
return nil, nil
}
// Iterator holding the iterator's state
type Iterator struct {
iterator rbt.Iterator
}
// Returns a stateful iterator whose elements are key/value pairs.
// 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.
// Next 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.
// Value 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.
// Key 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.
// Each 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() {
@ -161,7 +163,7 @@ func (m *Map) Each(f func(key interface{}, value interface{})) {
}
}
// Invokes the given function once for each element and returns a container
// 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.
func (m *Map) Map(f func(key1 interface{}, value1 interface{}) (interface{}, interface{})) *Map {
newMap := &Map{tree: rbt.NewWith(m.tree.Comparator)}
@ -173,7 +175,7 @@ func (m *Map) Map(f func(key1 interface{}, value1 interface{}) (interface{}, int
return newMap
}
// Returns a new container containing all elements for which the given function returns a true value.
// Select 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()
@ -185,7 +187,7 @@ func (m *Map) Select(f func(key interface{}, value interface{}) bool) *Map {
return newMap
}
// Passes each element of the container to the given function and
// Any 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()
@ -197,7 +199,7 @@ func (m *Map) Any(f func(key interface{}, value interface{}) bool) bool {
return false
}
// Passes each element of the container to the given function and
// All 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()
@ -209,7 +211,7 @@ func (m *Map) All(f func(key interface{}, value interface{}) bool) bool {
return true
}
// Passes each element of the container to the given function and returns
// 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.
func (m *Map) Find(f func(key interface{}, value interface{}) bool) (interface{}, interface{}) {
@ -222,6 +224,7 @@ func (m *Map) Find(f func(key interface{}, value interface{}) bool) (interface{}
return nil, nil
}
// String returns a string representation of container
func (m *Map) String() string {
str := "TreeMap\n"
str += m.tree.String()

@ -166,7 +166,7 @@ func TestMapEach(t *testing.T) {
m.Put("b", 2)
count := 0
m.Each(func(key interface{}, value interface{}) {
count += 1
count++
if actualValue, expectedValue := count, value; actualValue != expectedValue {
t.Errorf("Got %v expected %v", actualValue, expectedValue)
}

@ -40,32 +40,33 @@ func assertInterfaceImplementation() {
var _ sets.Set = (*Set)(nil)
}
// Set holds elements in go's native map
type Set struct {
items map[interface{}]struct{}
}
var itemExists = struct{}{}
// Instantiates a new empty set
// New instantiates a new empty set
func New() *Set {
return &Set{items: make(map[interface{}]struct{})}
}
// Adds the items (one or more) to the set.
// Add adds the items (one or more) to the set.
func (set *Set) Add(items ...interface{}) {
for _, item := range items {
set.items[item] = itemExists
}
}
// Removes the items (one or more) from the set.
// Remove removes the items (one or more) from the set.
func (set *Set) Remove(items ...interface{}) {
for _, item := range items {
delete(set.items, item)
}
}
// Check if items (one or more) are present in the set.
// Contains check if 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 {
@ -77,32 +78,33 @@ func (set *Set) Contains(items ...interface{}) bool {
return true
}
// Returns true if set does not contain any elements.
// Empty returns true if set does not contain any elements.
func (set *Set) Empty() bool {
return set.Size() == 0
}
// Returns number of elements within the set.
// Size returns number of elements within the set.
func (set *Set) Size() int {
return len(set.items)
}
// Clears all values in the set.
// Clear clears all values in the set.
func (set *Set) Clear() {
set.items = make(map[interface{}]struct{})
}
// Returns all items in the set.
// Values returns all items in the set.
func (set *Set) Values() []interface{} {
values := make([]interface{}, set.Size())
count := 0
for item := range set.items {
values[count] = item
count += 1
count++
}
return values
}
// String returns a string representation of container
func (set *Set) String() string {
str := "HashSet\n"
items := []string{}

@ -20,6 +20,7 @@ package sets
import "github.com/emirpasic/gods/containers"
// Set interface that all sets implement
type Set interface {
Add(elements ...interface{})
Remove(elements ...interface{})

@ -37,42 +37,43 @@ func assertInterfaceImplementation() {
var _ containers.IteratorWithIndex = (*Iterator)(nil)
}
// Set holds elements in a red-black tree
type Set struct {
tree *rbt.Tree
}
var itemExists = struct{}{}
// Instantiates a new empty set with the custom comparator.
// NewWith instantiates a new empty set with the custom comparator.
func NewWith(comparator utils.Comparator) *Set {
return &Set{tree: rbt.NewWith(comparator)}
}
// Instantiates a new empty set with the IntComparator, i.e. keys are of type int.
// NewWithIntComparator instantiates a new empty set with the IntComparator, i.e. keys are of type int.
func NewWithIntComparator() *Set {
return &Set{tree: rbt.NewWithIntComparator()}
}
// Instantiates a new empty set with the StringComparator, i.e. keys are of type string.
// NewWithStringComparator instantiates a new empty set with the StringComparator, i.e. keys are of type string.
func NewWithStringComparator() *Set {
return &Set{tree: rbt.NewWithStringComparator()}
}
// Adds the items (one or more) to the set.
// Add adds the items (one or more) to the set.
func (set *Set) Add(items ...interface{}) {
for _, item := range items {
set.tree.Put(item, itemExists)
}
}
// Removes the items (one or more) from the set.
// Remove removes the items (one or more) from the set.
func (set *Set) Remove(items ...interface{}) {
for _, item := range items {
set.tree.Remove(item)
}
}
// Check weather items (one or more) are present in the set.
// Contains checks 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 {
@ -84,57 +85,58 @@ func (set *Set) Contains(items ...interface{}) bool {
return true
}
// Returns true if set does not contain any elements.
// Empty returns true if set does not contain any elements.
func (set *Set) Empty() bool {
return set.tree.Size() == 0
}
// Returns number of elements within the set.
// Size returns number of elements within the set.
func (set *Set) Size() int {
return set.tree.Size()
}
// Clears all values in the set.
// Clear clears all values in the set.
func (set *Set) Clear() {
set.tree.Clear()
}
// Returns all items in the set.
// Values returns all items in the set.
func (set *Set) Values() []interface{} {
return set.tree.Keys()
}
// Iterator returns a stateful iterator whose values can be fetched by an index.
type Iterator struct {
index int
iterator rbt.Iterator
}
// Returns a stateful iterator whose values can be fetched by an index.
// Iterator holding the iterator's state
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.
// Next 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
iterator.index++
return iterator.iterator.Next()
}
// Returns the current element's value.
// Value 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.
// 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.
// Each 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() {
@ -142,7 +144,7 @@ func (set *Set) Each(f func(index int, value interface{})) {
}
}
// Invokes the given function once for each element and returns a
// Map 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)}
@ -153,7 +155,7 @@ func (set *Set) Map(f func(index int, value interface{}) interface{}) *Set {
return newSet
}
// Returns a new container containing all elements for which the given function returns a true value.
// Select 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()
@ -165,7 +167,7 @@ func (set *Set) Select(f func(index int, value interface{}) bool) *Set {
return newSet
}
// Passes each element of the container to the given function and
// Any 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()
@ -177,7 +179,7 @@ func (set *Set) Any(f func(index int, value interface{}) bool) bool {
return false
}
// Passes each element of the container to the given function and
// All 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()
@ -189,7 +191,7 @@ func (set *Set) All(f func(index int, value interface{}) bool) bool {
return true
}
// Passes each element of the container to the given function and returns
// 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.
func (set *Set) Find(f func(index int, value interface{}) bool) (int, interface{}) {
@ -202,6 +204,7 @@ func (set *Set) Find(f func(index int, value interface{}) bool) (int, interface{
return -1, nil
}
// String returns a string representation of container
func (set *Set) String() string {
str := "TreeSet\n"
items := []string{}

@ -43,21 +43,22 @@ func assertInterfaceImplementation() {
var _ containers.IteratorWithIndex = (*Iterator)(nil)
}
// Stack holds elements in an array-list
type Stack struct {
list *arraylist.List
}
// Instantiates a new empty stack
// New instantiates a new empty stack
func New() *Stack {
return &Stack{list: arraylist.New()}
}
// Pushes a value onto the top of the stack
// Push adds a value onto the top of the stack
func (stack *Stack) Push(value interface{}) {
stack.list.Add(value)
}
// Pops (removes) top element on stack and returns it, or nil if stack is empty.
// Pop removes top element on stack and returns it, or nil if stack is empty.
// Second return parameter is true, unless the stack was empty and there was nothing to pop.
func (stack *Stack) Pop() (value interface{}, ok bool) {
value, ok = stack.list.Get(stack.list.Size() - 1)
@ -65,28 +66,28 @@ func (stack *Stack) Pop() (value interface{}, ok bool) {
return
}
// Returns top element on the stack without removing it, or nil if stack is empty.
// Peek returns top element on the stack without removing it, or nil if stack is empty.
// Second return parameter is true, unless the stack was empty and there was nothing to peek.
func (stack *Stack) Peek() (value interface{}, ok bool) {
return stack.list.Get(stack.list.Size() - 1)
}
// Returns true if stack does not contain any elements.
// Empty returns true if stack does not contain any elements.
func (stack *Stack) Empty() bool {
return stack.list.Empty()
}
// Returns number of elements within the stack.
// Size returns number of elements within the stack.
func (stack *Stack) Size() int {
return stack.list.Size()
}
// Removes all elements from the stack.
// Clear removes all elements from the stack.
func (stack *Stack) Clear() {
stack.list.Clear()
}
// Returns all elements in the stack (LIFO order).
// Values returns all elements in the stack (LIFO order).
func (stack *Stack) Values() []interface{} {
size := stack.list.Size()
elements := make([]interface{}, size, size)
@ -96,37 +97,39 @@ func (stack *Stack) Values() []interface{} {
return elements
}
// Iterator returns a stateful iterator whose values can be fetched by an index.
type Iterator struct {
stack *Stack
index int
}
// Returns a stateful iterator whose values can be fetched by an index.
// Iterator 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.
// Next 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
iterator.index++
return iterator.stack.withinRange(iterator.index)
}
// Returns the current element's value.
// Value 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.
// Index returns the current element's index.
// Does not modify the state of the iterator.
func (iterator *Iterator) Index() int {
return iterator.index
}
// String returns a string representation of container
func (stack *Stack) String() string {
str := "ArrayStack\n"
values := []string{}

@ -44,21 +44,22 @@ func assertInterfaceImplementation() {
var _ containers.IteratorWithIndex = (*Iterator)(nil)
}
// Stack holds elements in a singly-linked-list
type Stack struct {
list *singlylinkedlist.List
}
// Instantiates a new empty stack
// New nnstantiates a new empty stack
func New() *Stack {
return &Stack{list: &singlylinkedlist.List{}}
}
// Pushes a value onto the top of the stack
// Push adds a value onto the top of the stack
func (stack *Stack) Push(value interface{}) {
stack.list.Prepend(value)
}
// Pops (removes) top element on stack and returns it, or nil if stack is empty.
// Pop removes top element on stack and returns it, or nil if stack is empty.
// Second return parameter is true, unless the stack was empty and there was nothing to pop.
func (stack *Stack) Pop() (value interface{}, ok bool) {
value, ok = stack.list.Get(0)
@ -66,63 +67,65 @@ func (stack *Stack) Pop() (value interface{}, ok bool) {
return
}
// Returns top element on the stack without removing it, or nil if stack is empty.
// Peek returns top element on the stack without removing it, or nil if stack is empty.
// Second return parameter is true, unless the stack was empty and there was nothing to peek.
func (stack *Stack) Peek() (value interface{}, ok bool) {
return stack.list.Get(0)
}
// Returns true if stack does not contain any elements.
// Empty returns true if stack does not contain any elements.
func (stack *Stack) Empty() bool {
return stack.list.Empty()
}
// Returns number of elements within the stack.
// Size returns number of elements within the stack.
func (stack *Stack) Size() int {
return stack.list.Size()
}
// Removes all elements from the stack.
// Clear removes all elements from the stack.
func (stack *Stack) Clear() {
stack.list.Clear()
}
// Returns all elements in the stack (LIFO order).
// Values returns all elements in the stack (LIFO order).
func (stack *Stack) Values() []interface{} {
return stack.list.Values()
}
// Iterator returns a stateful iterator whose values can be fetched by an index.
type Iterator struct {
stack *Stack
index int
}
// Returns a stateful iterator whose values can be fetched by an index.
// Iterator 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.
// Next 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
iterator.index++
return iterator.stack.withinRange(iterator.index)
}
// Returns the current element's value.
// Value 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.
// Index returns the current element's index.
// Does not modify the state of the iterator.
func (iterator *Iterator) Index() int {
return iterator.index
}
// String returns a string representation of container
func (stack *Stack) String() string {
str := "LinkedListStack\n"
values := []string{}

@ -28,6 +28,7 @@ package stacks
import "github.com/emirpasic/gods/containers"
// Stack interface that all stacks implement
type Stack interface {
Push(value interface{})
Pop() (value interface{}, ok bool)

@ -45,33 +45,34 @@ func assertInterfaceImplementation() {
var _ containers.IteratorWithIndex = (*Iterator)(nil)
}
// Heap holds elements in an array-list
type Heap struct {
list *arraylist.List
Comparator utils.Comparator
}
// Instantiates a new empty heap tree with the custom comparator.
// NewWith instantiates a new empty heap tree with the custom comparator.
func NewWith(comparator utils.Comparator) *Heap {
return &Heap{list: arraylist.New(), Comparator: comparator}
}
// Instantiates a new empty heap with the IntComparator, i.e. elements are of type int.
// NewWithIntComparator instantiates a new empty heap with the IntComparator, i.e. elements are of type int.
func NewWithIntComparator() *Heap {
return &Heap{list: arraylist.New(), Comparator: utils.IntComparator}
}
// Instantiates a new empty heap with the StringComparator, i.e. elements are of type string.
// NewWithStringComparator instantiates a new empty heap with the StringComparator, i.e. elements are of type string.
func NewWithStringComparator() *Heap {
return &Heap{list: arraylist.New(), Comparator: utils.StringComparator}
}
// Pushes a value onto the heap and bubbles it up accordingly.
// Push adds a value onto the heap and bubbles it up accordingly.
func (heap *Heap) Push(value interface{}) {
heap.list.Add(value)
heap.bubbleUp()
}
// Pops (removes) top element on heap and returns it, or nil if heap is empty.
// Pop removes top element on heap and returns it, or nil if heap is empty.
// Second return parameter is true, unless the heap was empty and there was nothing to pop.
func (heap *Heap) Pop() (value interface{}, ok bool) {
value, ok = heap.list.Get(0)
@ -85,63 +86,65 @@ func (heap *Heap) Pop() (value interface{}, ok bool) {
return
}
// Returns top element on the heap without removing it, or nil if heap is empty.
// Peek returns top element on the heap without removing it, or nil if heap is empty.
// Second return parameter is true, unless the heap was empty and there was nothing to peek.
func (heap *Heap) Peek() (value interface{}, ok bool) {
return heap.list.Get(0)
}
// Returns true if heap does not contain any elements.
// Empty returns true if heap does not contain any elements.
func (heap *Heap) Empty() bool {
return heap.list.Empty()
}
// Returns number of elements within the heap.
// Size returns number of elements within the heap.
func (heap *Heap) Size() int {
return heap.list.Size()
}
// Removes all elements from the heap.
// Clear removes all elements from the heap.
func (heap *Heap) Clear() {
heap.list.Clear()
}
// Returns all elements in the heap.
// Values returns all elements in the heap.
func (heap *Heap) Values() []interface{} {
return heap.list.Values()
}
// Iterator returns a stateful iterator whose values can be fetched by an index.
type Iterator struct {
heap *Heap
index int
}
// Returns a stateful iterator whose values can be fetched by an index.
// Iterator 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.
// Next 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
iterator.index++
return iterator.heap.withinRange(iterator.index)
}
// Returns the current element's value.
// Value 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.
// Index returns the current element's index.
// Does not modify the state of the iterator.
func (iterator *Iterator) Index() int {
return iterator.index
}
// String returns a string representation of container
func (heap *Heap) String() string {
str := "BinaryHeap\n"
values := []string{}

@ -50,12 +50,14 @@ const (
black, red color = true, false
)
// Tree holds elements of the red-black tree
type Tree struct {
Root *Node
size int
Comparator utils.Comparator
}
// Node is a single element within the tree
type Node struct {
Key interface{}
Value interface{}
@ -65,22 +67,22 @@ type Node struct {
Parent *Node
}
// Instantiates a red-black tree with the custom comparator.
// NewWith instantiates a red-black tree with the custom comparator.
func NewWith(comparator utils.Comparator) *Tree {
return &Tree{Comparator: comparator}
}
// Instantiates a red-black tree with the IntComparator, i.e. keys are of type int.
// NewWithIntComparator instantiates a red-black tree with the IntComparator, i.e. keys are of type int.
func NewWithIntComparator() *Tree {
return &Tree{Comparator: utils.IntComparator}
}
// Instantiates a red-black tree with the StringComparator, i.e. keys are of type string.
// NewWithStringComparator instantiates a red-black tree with the StringComparator, i.e. keys are of type string.
func NewWithStringComparator() *Tree {
return &Tree{Comparator: utils.StringComparator}
}
// Inserts node into the tree.
// Put inserts node into the tree.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Put(key interface{}, value interface{}) {
insertedNode := &Node{Key: key, Value: value, color: red}
@ -114,10 +116,10 @@ func (tree *Tree) Put(key interface{}, value interface{}) {
insertedNode.Parent = node
}
tree.insertCase1(insertedNode)
tree.size += 1
tree.size++
}
// Searches the node in the tree by key and returns its value or nil if key is not found in tree.
// Get searches the node in the tree by key and returns its value or nil if key is not found in tree.
// Second return parameter is true if key was found, otherwise false.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Get(key interface{}) (value interface{}, found bool) {
@ -128,7 +130,7 @@ func (tree *Tree) Get(key interface{}) (value interface{}, found bool) {
return nil, false
}
// Remove the node from the tree by key.
// Remove remove the node from the tree by key.
// Key should adhere to the comparator's type assertion, otherwise method panics.
func (tree *Tree) Remove(key interface{}) {
var child *Node
@ -157,20 +159,20 @@ func (tree *Tree) Remove(key interface{}) {
child.color = black
}
}
tree.size -= 1
tree.size--
}
// Returns true if tree does not contain any nodes
// Empty returns true if tree does not contain any nodes
func (tree *Tree) Empty() bool {
return tree.size == 0
}
// Returns number of nodes in the tree.
// Size returns number of nodes in the tree.
func (tree *Tree) Size() int {
return tree.size
}
// Returns all keys in-order
// Keys returns all keys in-order
func (tree *Tree) Keys() []interface{} {
keys := make([]interface{}, tree.size)
for i, node := range tree.inOrder() {
@ -179,7 +181,7 @@ func (tree *Tree) Keys() []interface{} {
return keys
}
// Returns all values in-order based on the key.
// Values returns all values in-order based on the key.
func (tree *Tree) Values() []interface{} {
values := make([]interface{}, tree.size)
for i, node := range tree.inOrder() {
@ -188,7 +190,7 @@ func (tree *Tree) Values() []interface{} {
return values
}
// Returns the left-most (min) node or nil if tree is empty.
// Left returns the left-most (min) node or nil if tree is empty.
func (tree *Tree) Left() *Node {
var parent *Node
current := tree.Root
@ -199,7 +201,7 @@ func (tree *Tree) Left() *Node {
return parent
}
// Returns the right-most (max) node or nil if tree is empty.
// Right returns the right-most (max) node or nil if tree is empty.
func (tree *Tree) Right() *Node {
var parent *Node
current := tree.Root
@ -210,7 +212,7 @@ func (tree *Tree) Right() *Node {
return parent
}
// Find floor node of the input key, return the floor node or nil if no ceiling is found.
// Floor Finds floor node of the input key, return the floor node or nil if no ceiling is found.
// Second return parameter is true if floor was found, otherwise false.
//
// Floor node is defined as the largest node that is smaller than or equal to the given node.
@ -239,7 +241,7 @@ func (tree *Tree) Floor(key interface{}) (floor *Node, found bool) {
return nil, false
}
// Find ceiling node of the input key, return the ceiling node or nil if no ceiling is found.
// Ceiling finds ceiling node of the input key, return the ceiling node or nil if no ceiling is found.
// Second return parameter is true if ceiling was found, otherwise false.
//
// Ceiling node is defined as the smallest node that is larger than or equal to the given node.
@ -268,23 +270,24 @@ func (tree *Tree) Ceiling(key interface{}) (ceiling *Node, found bool) {
return nil, false
}
// Removes all nodes from the tree.
// Clear removes all nodes from the tree.
func (tree *Tree) Clear() {
tree.Root = nil
tree.size = 0
}
// Iterator holding the iterator's state
type Iterator struct {
tree *Tree
left *Node
}
// Returns a stateful iterator whose elements are key/value pairs.
// Iterator 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.
// Next 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 {
@ -311,18 +314,19 @@ func (iterator *Iterator) Next() bool {
return false
}
// Returns the current element's value.
// Value 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.
// Key returns the current element's key.
// Does not modify the state of the iterator.
func (iterator *Iterator) Key() interface{} {
return iterator.left.Key
}
// String returns a string representation of container
func (tree *Tree) String() string {
str := "RedBlackTree\n"
if !tree.Empty() {
@ -352,7 +356,7 @@ func (tree *Tree) inOrder() []*Node {
currentPop, _ := stack.Pop()
current = currentPop.(*Node)
nodes[count] = current
count += 1
count++
current = current.Right
} else {
done = true
@ -363,6 +367,7 @@ func (tree *Tree) inOrder() []*Node {
return nodes
}
// String returns a string representation of container
func output(node *Node, prefix string, isTail bool, str *string) {
if node.Right != nil {
newPrefix := prefix
@ -427,9 +432,8 @@ func (node *Node) sibling() *Node {
}
if node == node.Parent.Left {
return node.Parent.Right
} else {
return node.Parent.Left
}
return node.Parent.Left
}
func (tree *Tree) rotateLeft(node *Node) {
@ -532,9 +536,8 @@ func (node *Node) maximumNode() *Node {
func (tree *Tree) deleteCase1(node *Node) {
if node.Parent == nil {
return
} else {
tree.deleteCase2(node)
}
tree.deleteCase2(node)
}
func (tree *Tree) deleteCase2(node *Node) {

@ -220,7 +220,7 @@ func TestRedBlackTreeIterator1(t *testing.T) {
it := tree.Iterator()
count := 0
for it.Next() {
count += 1
count++
index := it.Key()
switch index {
case count:
@ -246,7 +246,7 @@ func TestRedBlackTreeIterator2(t *testing.T) {
it := tree.Iterator()
count := 0
for it.Next() {
count += 1
count++
index := it.Key()
switch index {
case count:
@ -277,7 +277,7 @@ func TestRedBlackTreeIterator3(t *testing.T) {
it = tree.Iterator()
count := 0
for it.Next() {
count += 1
count++
index := it.Key()
switch index {
case count:
@ -311,7 +311,7 @@ func TestRedBlackTreeIterator4(t *testing.T) {
it := tree.Iterator()
count := 0
for it.Next() {
count += 1
count++
value := it.Value()
switch value {
case count:

@ -28,6 +28,7 @@ package trees
import "github.com/emirpasic/gods/containers"
// Tree interface that all trees implement
type Tree interface {
containers.Container
// Empty() bool

@ -35,6 +35,7 @@ package utils
// 1, if a > b
type Comparator func(a, b interface{}) int
// IntComparator provides a basic comparison on ints
func IntComparator(a, b interface{}) int {
aInt := a.(int)
bInt := b.(int)
@ -48,6 +49,7 @@ func IntComparator(a, b interface{}) int {
}
}
// StringComparator provides a fast comparison on strings
func StringComparator(a, b interface{}) int {
s1 := a.(string)
s2 := b.(string)

@ -30,7 +30,7 @@ package utils
import "github.com/emirpasic/gods/utils/timsort"
// Sorts values (in-place) using timsort
// Sort sorts values (in-place) using timsort
func Sort(values []interface{}, comparator Comparator) {
less := func(a, b interface{}) bool { return comparator(a, b) < 0 }
timsort.Sort(values, less)

@ -64,7 +64,7 @@ const (
* of the minimum stack length required as a function of the length
* of the array being sorted and the minimum merge sequence length.
*/
_MIN_MERGE = 32
minMerge = 32
// mk: tried higher MIN_MERGE and got slower sorting (348->375)
// c_MIN_MERGE = 64
@ -72,7 +72,7 @@ const (
* When we get into galloping mode, we stay there until both runs win less
* often than c_MIN_GALLOP consecutive times.
*/
_MIN_GALLOP = 7
minGallop = 7
/**
* Maximum initial size of tmp array, which is used for merging. The array
@ -81,10 +81,10 @@ const (
* Unlike Tim's original C version, we do not allocate this much storage
* when sorting smaller arrays. This change was required for performance.
*/
_INITIAL_TMP_STORAGE_LENGTH = 256
initialTmpStorageLength = 256
)
// Delegate type that sorting uses as a comparator
// LessThan delegate type for sorting uses as a comparator
type LessThan func(a, b interface{}) bool
type timSortHandler struct {
@ -132,23 +132,23 @@ type timSortHandler struct {
* @param a the array to be sorted
* @param c the comparator to determine the order of the sort
*/
func newTimSort(a []interface{}, lt LessThan) (self *timSortHandler) {
self = new(timSortHandler)
func newTimSort(a []interface{}, lt LessThan) (tsh *timSortHandler) {
tsh = new(timSortHandler)
self.a = a
self.lt = lt
self.minGallop = _MIN_GALLOP
self.stackSize = 0
tsh.a = a
tsh.lt = lt
tsh.minGallop = minGallop
tsh.stackSize = 0
// Allocate temp storage (which may be increased later if necessary)
len := len(a)
tmpSize := _INITIAL_TMP_STORAGE_LENGTH
tmpSize := initialTmpStorageLength
if len < 2*tmpSize {
tmpSize = len / 2
}
self.tmp = make([]interface{}, tmpSize)
tsh.tmp = make([]interface{}, tmpSize)
/*
* Allocate runs-to-be-merged stack (which cannot be expanded). The
@ -171,13 +171,13 @@ func newTimSort(a []interface{}, lt LessThan) (self *timSortHandler) {
stackLen = 19
}
self.runBase = make([]int, stackLen)
self.runLen = make([]int, stackLen)
tsh.runBase = make([]int, stackLen)
tsh.runLen = make([]int, stackLen)
return self
return tsh
}
// Sorts an array using the provided comparator
// Sort sorts an array using the provided comparator
func Sort(a []interface{}, lt LessThan) (err error) {
lo := 0
hi := len(a)
@ -188,7 +188,7 @@ func Sort(a []interface{}, lt LessThan) (err error) {
}
// If array is small, do a "mini-TimSort" with no merges
if nRemaining < _MIN_MERGE {
if nRemaining < minMerge {
initRunLen, err := countRunAndMakeAscending(a, lo, hi, lt)
if err != nil {
return err
@ -243,7 +243,7 @@ func Sort(a []interface{}, lt LessThan) (err error) {
// Merge all remaining runs to complete sort
if lo != hi {
return errors.New("lo==hi!")
return errors.New("lo==hi")
}
if err = ts.mergeForceCollapse(); err != nil {
@ -426,7 +426,7 @@ func minRunLength(n int) (int, error) {
return 0, errors.New("n >= 0")
}
r := 0 // Becomes 1 if any 1 bits are shifted off
for n >= _MIN_MERGE {
for n >= minMerge {
r |= (n & 1)
n >>= 1
}
@ -439,10 +439,10 @@ func minRunLength(n int) (int, error) {
* @param runBase index of the first element in the run
* @param runLen the number of elements in the run
*/
func (self *timSortHandler) pushRun(runBase, runLen int) {
self.runBase[self.stackSize] = runBase
self.runLen[self.stackSize] = runLen
self.stackSize++
func (tsh *timSortHandler) pushRun(runBase, runLen int) {
tsh.runBase[tsh.stackSize] = runBase
tsh.runLen[tsh.stackSize] = runLen
tsh.stackSize++
}
/**
@ -456,18 +456,18 @@ func (self *timSortHandler) pushRun(runBase, runLen int) {
* so the invariants are guaranteed to hold for i < stackSize upon
* entry to the method.
*/
func (self *timSortHandler) mergeCollapse() (err error) {
for self.stackSize > 1 {
n := self.stackSize - 2
if n > 0 && self.runLen[n-1] <= self.runLen[n]+self.runLen[n+1] {
if self.runLen[n-1] < self.runLen[n+1] {
func (tsh *timSortHandler) mergeCollapse() (err error) {
for tsh.stackSize > 1 {
n := tsh.stackSize - 2
if n > 0 && tsh.runLen[n-1] <= tsh.runLen[n]+tsh.runLen[n+1] {
if tsh.runLen[n-1] < tsh.runLen[n+1] {
n--
}
if err = self.mergeAt(n); err != nil {
if err = tsh.mergeAt(n); err != nil {
return
}
} else if self.runLen[n] <= self.runLen[n+1] {
if err = self.mergeAt(n); err != nil {
} else if tsh.runLen[n] <= tsh.runLen[n+1] {
if err = tsh.mergeAt(n); err != nil {
return
}
} else {
@ -481,13 +481,13 @@ func (self *timSortHandler) mergeCollapse() (err error) {
* Merges all runs on the stack until only one remains. This method is
* called once, to complete the sort.
*/
func (self *timSortHandler) mergeForceCollapse() (err error) {
for self.stackSize > 1 {
n := self.stackSize - 2
if n > 0 && self.runLen[n-1] < self.runLen[n+1] {
func (tsh *timSortHandler) mergeForceCollapse() (err error) {
for tsh.stackSize > 1 {
n := tsh.stackSize - 2
if n > 0 && tsh.runLen[n-1] < tsh.runLen[n+1] {
n--
}
if err = self.mergeAt(n); err != nil {
if err = tsh.mergeAt(n); err != nil {
return
}
}
@ -501,8 +501,8 @@ func (self *timSortHandler) mergeForceCollapse() (err error) {
*
* @param i stack index of the first of the two runs to merge
*/
func (self *timSortHandler) mergeAt(i int) (err error) {
if self.stackSize < 2 {
func (tsh *timSortHandler) mergeAt(i int) (err error) {
if tsh.stackSize < 2 {
return errors.New("stackSize >= 2")
}
@ -510,14 +510,14 @@ func (self *timSortHandler) mergeAt(i int) (err error) {
return errors.New(" i >= 0")
}
if i != self.stackSize-2 && i != self.stackSize-3 {
if i != tsh.stackSize-2 && i != tsh.stackSize-3 {
return errors.New("if i == stackSize - 2 || i == stackSize - 3")
}
base1 := self.runBase[i]
len1 := self.runLen[i]
base2 := self.runBase[i+1]
len2 := self.runLen[i+1]
base1 := tsh.runBase[i]
len1 := tsh.runLen[i]
base2 := tsh.runBase[i+1]
len2 := tsh.runLen[i+1]
if len1 <= 0 || len2 <= 0 {
return errors.New("len1 > 0 && len2 > 0")
@ -532,18 +532,18 @@ func (self *timSortHandler) mergeAt(i int) (err error) {
* run now, also slide over the last run (which isn't involved
* in this merge). The current run (i+1) goes away in any case.
*/
self.runLen[i] = len1 + len2
if i == self.stackSize-3 {
self.runBase[i+1] = self.runBase[i+2]
self.runLen[i+1] = self.runLen[i+2]
tsh.runLen[i] = len1 + len2
if i == tsh.stackSize-3 {
tsh.runBase[i+1] = tsh.runBase[i+2]
tsh.runLen[i+1] = tsh.runLen[i+2]
}
self.stackSize--
tsh.stackSize--
/*
* Find where the first element of run2 goes in run1. Prior elements
* in run1 can be ignored (because they're already in place).
*/
k, err := gallopRight(self.a[base2], self.a, base1, len1, 0, self.lt)
k, err := gallopRight(tsh.a[base2], tsh.a, base1, len1, 0, tsh.lt)
if err != nil {
return err
}
@ -560,7 +560,7 @@ func (self *timSortHandler) mergeAt(i int) (err error) {
* Find where the last element of run1 goes in run2. Subsequent elements
* in run2 can be ignored (because they're already in place).
*/
len2, err = gallopLeft(self.a[base1+len1-1], self.a, base2, len2, len2-1, self.lt)
len2, err = gallopLeft(tsh.a[base1+len1-1], tsh.a, base2, len2, len2-1, tsh.lt)
if err != nil {
return
}
@ -573,14 +573,14 @@ func (self *timSortHandler) mergeAt(i int) (err error) {
// Merge remaining runs, using tmp array with min(len1, len2) elements
if len1 <= len2 {
err = self.mergeLo(base1, len1, base2, len2)
err = tsh.mergeLo(base1, len1, base2, len2)
if err != nil {
return errors.New(fmt.Sprintf("mergeLo: %v", err))
return errors.New(fmt.Errorf("mergeLo: %v", err).Error())
}
} else {
err = self.mergeHi(base1, len1, base2, len2)
err = tsh.mergeHi(base1, len1, base2, len2)
if err != nil {
return errors.New(fmt.Sprintf("mergeHi: %v", err))
return errors.New(fmt.Errorf("mergeHi: %v", err).Error())
}
}
return
@ -771,14 +771,14 @@ func gallopRight(key interface{}, a []interface{}, base, len, hint int, c LessTh
* (must be aBase + aLen)
* @param len2 length of second run to be merged (must be > 0)
*/
func (self *timSortHandler) mergeLo(base1, len1, base2, len2 int) (err error) {
func (tsh *timSortHandler) mergeLo(base1, len1, base2, len2 int) (err error) {
if len1 <= 0 || len2 <= 0 || base1+len1 != base2 {
return errors.New(" len1 > 0 && len2 > 0 && base1 + len1 == base2")
}
// Copy first run into temp array
a := self.a // For performance
tmp := self.ensureCapacity(len1)
a := tsh.a // For performance
tmp := tsh.ensureCapacity(len1)
copy(tmp, a[base1:base1+len1])
@ -801,8 +801,8 @@ func (self *timSortHandler) mergeLo(base1, len1, base2, len2 int) (err error) {
return
}
lt := self.lt // Use local variable for performance
minGallop := self.minGallop // " " " " "
lt := tsh.lt // Use local variable for performance
minGallop := tsh.minGallop // " " " " "
outer:
for {
@ -895,7 +895,7 @@ outer:
break outer
}
minGallop--
if count1 < _MIN_GALLOP && count2 < _MIN_GALLOP {
if count1 < minGallop && count2 < minGallop {
break
}
}
@ -908,7 +908,7 @@ outer:
if minGallop < 1 {
minGallop = 1
}
self.minGallop = minGallop // Write back to field
tsh.minGallop = minGallop // Write back to field
if len1 == 1 {
@ -943,14 +943,14 @@ outer:
* (must be aBase + aLen)
* @param len2 length of second run to be merged (must be > 0)
*/
func (self *timSortHandler) mergeHi(base1, len1, base2, len2 int) (err error) {
func (tsh *timSortHandler) mergeHi(base1, len1, base2, len2 int) (err error) {
if len1 <= 0 || len2 <= 0 || base1+len1 != base2 {
return errors.New("len1 > 0 && len2 > 0 && base1 + len1 == base2;")
}
// Copy second run into temp array
a := self.a // For performance
tmp := self.ensureCapacity(len2)
a := tsh.a // For performance
tmp := tsh.ensureCapacity(len2)
copy(tmp, a[base2:base2+len2])
@ -976,8 +976,8 @@ func (self *timSortHandler) mergeHi(base1, len1, base2, len2 int) (err error) {
return
}
lt := self.lt // Use local variable for performance
minGallop := self.minGallop // " " " " "
lt := tsh.lt // Use local variable for performance
minGallop := tsh.minGallop // " " " " "
outer:
for {
@ -1072,7 +1072,7 @@ outer:
}
minGallop--
if count1 < _MIN_GALLOP && count2 < _MIN_GALLOP {
if count1 < minGallop && count2 < minGallop {
break
}
}
@ -1086,7 +1086,7 @@ outer:
minGallop = 1
}
self.minGallop = minGallop // Write back to field
tsh.minGallop = minGallop // Write back to field
if len2 == 1 {
if len1 <= 0 {
@ -1121,8 +1121,8 @@ outer:
* @param minCapacity the minimum required capacity of the tmp array
* @return tmp, whether or not it grew
*/
func (self *timSortHandler) ensureCapacity(minCapacity int) []interface{} {
if len(self.tmp) < minCapacity {
func (tsh *timSortHandler) ensureCapacity(minCapacity int) []interface{} {
if len(tsh.tmp) < minCapacity {
// Compute smallest power of 2 > minCapacity
newSize := minCapacity
newSize |= newSize >> 1
@ -1135,14 +1135,14 @@ func (self *timSortHandler) ensureCapacity(minCapacity int) []interface{} {
if newSize < 0 { // Not bloody likely!
newSize = minCapacity
} else {
ns := len(self.a) / 2
ns := len(tsh.a) / 2
if ns < newSize {
newSize = ns
}
}
self.tmp = make([]interface{}, newSize)
tsh.tmp = make([]interface{}, newSize)
}
return self.tmp
return tsh.tmp
}

Loading…
Cancel
Save