finished slice stuff, started queues

main
RageCage64 2 years ago
parent 21e82bb2b5
commit 337e85e173

@ -0,0 +1,8 @@
.PHONY: install_tools
install_tools:
go install github.com/google/addlicense@latest
go install github.com/jordanlewis/gcassert/cmd/gcassert@latest
.PHONY: addlicense
addlicense:
addlicense -c "Braydon Kains" -l mit .

@ -1,5 +1,5 @@
# collections-go
A dependency-free package of generic Go collection data structures. Compatible with Go 1.18 and above. Strives for the most optimal solutions available with lowest number of allocations.
A dependency-free package of generic Go collection data structures. Compatible with Go 1.18 and above. Strives for the most optimal solutions available with lowest number of heap allocations.
Contributions are not currently open as this project is in active early development.

@ -1,9 +0,0 @@
package collections
// A UnaryPredicate is a function that takes a single element of type
// T and returns a boolean.
type UnaryPredicate[T any] func(T) bool
// A UnaryOperator is a function that takes a single element of type
// T and returns an element of type T.
type UnaryOperator[T any] func(T) T

@ -0,0 +1,124 @@
// Copyright (c) 2023 Braydon Kains
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package collections
import "errors"
type LLNode[T any] struct {
Value T
Prev *LLNode[T]
Next *LLNode[T]
}
func (head *LLNode[T]) Len() int {
curr := head
n := 0
for curr != nil {
n++
curr = curr.Next
}
return n
}
func (head *LLNode[T]) Range() []T {
llLen := head.Len()
result := make([]T, llLen)
curr := head
for i := 0; i < llLen; i++ {
result[i] = curr.Value
curr = curr.Next
}
return result
}
func (head *LLNode[T]) AddToEnd(val T) *LLNode[T] {
curr := head
for curr.Next != nil {
curr = curr.Next
}
node := &LLNode[T]{Value: val, Prev: curr}
curr.Next = node
return node
}
func (head *LLNode[T]) AddToStart(val T) *LLNode[T] {
node := &LLNode[T]{Value: val, Next: head}
head.Prev = node
return node
}
func (n *LLNode[T]) RemoveSelf() {
if n.Prev != nil {
n.Prev.Next = n.Next
}
if n.Next != nil {
n.Next.Prev = n.Prev
}
}
// A FIFO queue.
type Queue[T any] struct {
Head *LLNode[T]
}
func (q *Queue[T]) Enqueue(val T) {
if q.Head == nil {
q.Head = &LLNode[T]{Value: val}
} else {
q.Head.AddToEnd(val)
}
}
var ErrQueueEmpty = errors.New("collections: the queue is empty")
func (q *Queue[T]) Dequeue() (T, error) {
if q.Head == nil {
return *new(T), ErrQueueEmpty
}
result := q.Head
q.Head = result.Next
return result.Value, nil
}
// A Stack, aka FILO queue.
type Stack[T any] struct {
Head *LLNode[T]
}
func (s *Stack[T]) Push(val T) {
if s.Head == nil {
s.Head = &LLNode[T]{Value: val}
} else {
node := s.Head.AddToStart(val)
s.Head = node
}
}
var ErrStackEmpty = errors.New("the stack is empty")
func (s *Stack[T]) Pop() (T, error) {
if s.Head == nil {
return *new(T), ErrStackEmpty
}
oldHead := s.Head
s.Head = s.Head.Next
oldHead.RemoveSelf()
return oldHead.Value, nil
}

@ -1,3 +1,22 @@
// Copyright (c) 2023 Braydon Kains
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package collections
// Set is a type alias over a map to an empty struct. This allows a nice
@ -11,15 +30,30 @@ type Set[T comparable] map[T]struct{}
//
// Time Complexity: O(n)
// Space Complexity: O(n)
// Allocations: 1 set, n elements.
// Allocations: 1 slice, n elements (variadic function argument). 1 set, n elements.
func NewSet[T comparable](elements ...T) Set[T] {
set := make(Set[T])
set := make(Set[T], len(elements))
for i := 0; i < len(elements); i++ {
set.Add(elements[i])
}
return set
}
// Initialize a new Set with a slice. Good for if you already have a slice and want a
// set with its values (saves an allocation over NewSet). This function will toss
// duplicate values, see NewSetSaveDuplicates if you need to retain duplicate info.
//
// Time Complexity: O(n)
// Space Complexity: O(n)
// Allocations: 1 slice, n elements (variadic function argument). 1 set, n elements.
func NewSetFromSlice[T comparable](sl []T) Set[T] {
set := make(Set[T], len(sl))
for i := 0; i < len(sl); i++ {
set.Add(sl[i])
}
return set
}
// Initialize a new set while preserving the elements that were found to be duplicate.
// The duplicate slice will be nil if there are no duplicates to save on allocations.
//
@ -29,7 +63,7 @@ func NewSet[T comparable](elements ...T) Set[T] {
// Allocations (worst case): 1 set, n/2 elements, 2 slices, one with n-1 space, the
// second is the first one resized if necessary.
func NewSetSaveDuplicates[T comparable](slice []T) (Set[T], []T) {
set := make(Set[T])
set := make(Set[T], len(slice))
var dupes []T = nil
dupesIdx := 0
for _, el := range slice {
@ -71,7 +105,7 @@ func (set Set[T]) ToSlice() []T {
//
// Time Complexity: O(1)
// Space Complexity: O(1)
// Allocations: 1 elements
// Allocations: Set resize
func (s Set[T]) Add(el T) {
s[el] = struct{}{}
}
@ -80,7 +114,7 @@ func (s Set[T]) Add(el T) {
//
// Time Complexity: O(1)
// Space Complexity: O(1)
// Allocations: None
// Allocations: Set resize
func (s Set[T]) Remove(el T) {
delete(s, el)
}
@ -99,9 +133,9 @@ func (s Set[T]) Contains(el T) bool {
//
// Time Complexity: O(n)
// Space Complexity: O(n)
// Allocations: 1 set, n elements
// Allocations: 1 set of n elements
func (s Set[T]) Clone() Set[T] {
clone := make(Set[T])
clone := make(Set[T], len(s))
for el := range s {
clone.Add(el)
}

@ -1,3 +1,22 @@
// Copyright (c) 2023 Braydon Kains
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package collections_test
import (

@ -1,8 +1,42 @@
// Copyright (c) 2023 Braydon Kains
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package collections
/*****************
This section contains the alias API, which allows for receiver-style calling
convention.
The arguments for higher-order function algorithms.
*****************/
// UnaryPredicate is a function that takes a single element of type
// T and returns a boolean. Used for filtering operations.
type UnaryPredicate[T any] func(T) bool
// UnaryOperator is a function that takes a single element of type
// T and returns an element of type T.
type UnaryOperator[T any] func(T) T
// Reducer is a function that takes an accumulator and the current
// element of the slice.
type Reducer[Acc any, T any] func(accumulator Acc, current T)
/*****************
The alias API, which allows for receiver-style calling convention.
*****************/
// Slice is an alias over a Go slice that enables a direct receiver-style API.
@ -14,12 +48,30 @@ func (sl Slice[T]) Contains(needle T) bool {
return SliceContains(sl, needle)
}
// Check if a slice contains each individual element from another slice. Order
// is not considered. To consider order, use Subset. Calls SliceContainsEach.
func (sl Slice[T]) ContainsEach(needles []T) bool {
return SliceContainsEach(sl, needles)
}
// Check if another slice is a (non-strict) subset of the slice. Calls SliceSubset.
func (sl Slice[T]) Subset(sub []T) bool {
return SliceSubset(sl, sub)
}
// Run an operator on every element in the slice, and return a slice that
// contains the result of every operation. Calls SliceMap.
func (sl Slice[T]) Map(op UnaryOperator[T]) Slice[T] {
return SliceMap(sl, op)
}
// Run a predicate on every element in the slice, and return a slice
// that contains every element for which the predicate was true. Calls
// SliceFilter.
func (sl Slice[T]) Filter(pred UnaryPredicate[T]) Slice[T] {
return SliceFilter(sl, pred)
}
// AnySlice is an alias over a Go slice that does not enforce T satisfying
// comparable. Any method that relies on comparison of elements is not
// available for AnySlice.
@ -31,6 +83,13 @@ func (sl AnySlice[T]) Map(op UnaryOperator[T]) AnySlice[T] {
return SliceMap(sl, op)
}
// Run a predicate on every element in the slice, and return a slice
// that contains every element for which the predicate was true. Calls
// SliceFilter.
func (sl AnySlice[T]) Filter(pred UnaryPredicate[T]) AnySlice[T] {
return SliceFilter(sl, pred)
}
/*****************
This section contains the direct API, which is a more traditional Go style
API.
@ -40,7 +99,7 @@ API.
//
// Time Complexity: O(n)
// Space Complexity: O(1)
// Allocations: None.
// Allocations: None
func SliceContains[T comparable](haystack []T, needle T) bool {
for i := 0; i < len(haystack); i++ {
if haystack[i] == needle {
@ -50,9 +109,74 @@ func SliceContains[T comparable](haystack []T, needle T) bool {
return false
}
// Check if a slice contains each individual element of another slice. Order
// is not considered. To consider order, use SliceSubset.
//
// Time Complexity: O(n)
// Space Complexity: O(n)
// Allocations: 1 map, m (needles argument) elements
func SliceContainsEach[T comparable](haystack []T, needles []T) bool {
// Allocating a map here is better for time complexity and allocations,
// since the alternative is working with a slice that would need to be
// searched through and in most cases resized when elements are found.
needleSet := make(map[T]struct{}, len(needles))
for i := 0; i < len(needles); i++ {
needleSet[needles[i]] = struct{}{}
}
for i := 0; i < len(haystack); i++ {
delete(needleSet, haystack[i])
}
return len(needleSet) == 0
}
// Check if another slice is a subset of the slice. This check is non-strict.
// For a strict subset, use SliceSubsetStrict.
//
// Time Complexity: O(n)
// Space Complexity: O(1)
// Allocations: None
func SliceSubset[T comparable](sl []T, sub []T) bool {
if len(sub) > len(sl) {
return false
}
return subset(sl, sub)
}
// Check if another slice is a strict subset of the slice. That is, the other
// slice is a subset but not equal to the main slice.
//
// Time Complexity: O(n)
// Space Complexity: O(1)
// Allocations: None
func SliceSubsetStrict[T comparable](sl []T, sub []T) bool {
// Strict subset means the two slices can't be the same size.
if len(sub) > len(sl)-1 {
return false
}
return subset(sl, sub)
}
func subset[T comparable](sl []T, sub []T) bool {
subIdx := 0
for i := 0; i < len(sl); i++ {
if sl[i] == sub[subIdx] {
if subIdx == len(sub)-1 {
return true
}
subIdx++
} else {
subIdx = 0
}
}
return false
}
// Run an operator on every element in the slice, and return a slice that
// contains the result of every operation.
//
// Sometimes known by other names: Transform, Select
//
// Time Complexity: O(n * m) (where m = complexity of operator)
// Space Complexity: O(n)
// Allocations: 1 slice, n elements.
@ -67,6 +191,8 @@ func SliceMap[T any](sl []T, op UnaryOperator[T]) []T {
// Run a predicate on every element in the slice, and return a slice
// that contains every element for which the predicate was true.
//
// Sometimes known by other names: Where,
//
// Time Complexity: O(n * m) (where m = complexity of predicate)
// Space Complexity: O(n)
// Allocations: 2 slice, first with n elements, second is the first slice
@ -85,3 +211,23 @@ func SliceFilter[T any](sl []T, pred UnaryPredicate[T]) []T {
}
return result
}
// With a starting accumulator, run the reducer operator with the accumulator
// and each element of the slice. The accumulator should be a slice or a pointer
// to a value so the change is reflected throughout the combination.
//
// Sometimes known by other names: Fold, Aggregate, Combine
//
// Time Complexity: O(n * m) (where m = complexity of reducer)
// Space Complexity: O(1)
// Allocations: None
func SliceReduce[Acc any, T any](
sl []T,
accumulator Acc,
folder Reducer[Acc, T],
) Acc {
for i := 0; i < len(sl); i++ {
folder(accumulator, sl[i])
}
return accumulator
}

@ -1,3 +1,22 @@
// Copyright (c) 2023 Braydon Kains
//
// Permission is hereby granted, free of charge, to any person obtaining a copy of
// this software and associated documentation files (the "Software"), to deal in
// the Software without restriction, including without limitation the rights to
// use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of
// the Software, and to permit persons to whom the Software is furnished to do so,
// subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in all
// copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
// FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
// COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
// IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
// CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package collections_test
import (
@ -7,7 +26,7 @@ import (
"github.com/RageCage64/go-assert"
)
func TestSliceContainsDirect(t *testing.T) {
func TestSliceContains(t *testing.T) {
x := []int{1, 2, 3}
assert.Assert(t, collections.SliceContains(x, 1), "it didn't")
}

Loading…
Cancel
Save