diff --git a/go.mod b/go.mod new file mode 100644 index 0000000..f9e8a58 --- /dev/null +++ b/go.mod @@ -0,0 +1,9 @@ +module github.com/474420502/focus + +go 1.12 + +require ( + github.com/Pallinder/go-randomdata v1.1.0 + github.com/davecgh/go-spew v1.1.1 + github.com/emirpasic/gods v1.12.0 +) diff --git a/go.sum b/go.sum new file mode 100644 index 0000000..b3f692e --- /dev/null +++ b/go.sum @@ -0,0 +1,6 @@ +github.com/Pallinder/go-randomdata v1.1.0 h1:gUubB1IEUliFmzjqjhf+bgkg1o6uoFIkRsP3VrhEcx8= +github.com/Pallinder/go-randomdata v1.1.0/go.mod h1:yHmJgulpD2Nfrm0cR9tI/+oAgRqCQQixsA8HyRZfV9Y= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/emirpasic/gods v1.12.0 h1:QAUIPSaCu4G+POclxeqb3F+WPpdKqFGlw36+yOzGlrg= +github.com/emirpasic/gods v1.12.0/go.mod h1:YfzfFFoVP/catgzJb4IKIqXjX78Ha8FMSDh3ymbK86o= diff --git a/list/arraylist/arraylist.go b/list/arraylist/arraylist.go index 3461837..17eb610 100644 --- a/list/arraylist/arraylist.go +++ b/list/arraylist/arraylist.go @@ -1,108 +1,218 @@ package arraylist +import ( + "fmt" + "strings" + + "github.com/emirpasic/gods/lists" + "github.com/emirpasic/gods/utils" +) + +func assertListImplementation() { + var _ lists.List = (*ArrayList)(nil) +} + type ArrayList struct { data []interface{} - - headIndex uint - nextIndex uint - - size uint - - reserveHead uint - reserveLimit uint - - growSize uint - shrinkSize uint + size int } -func New() *ArrayList { - al := &ArrayList{} - al.reserveHead = 2 - al.reserveLimit = 256 - al.headIndex = al.reserveHead - al.nextIndex = al.headIndex +const ( + growthFactor = float32(2.0) // growth by 100% + shrinkFactor = float32(0.25) // shrink when size is 25% of capacity (0 means never shrink) +) - al.data = make([]interface{}, 8, 8) - return al -} - -func (l *ArrayList) Size() uint { - return l.size -} - -func (l *ArrayList) grow() { - newsize := uint(len(l.data)) << 1 - - if l.reserveHead < l.reserveLimit { - l.reserveHead = l.reserveHead << 1 +// New instantiates a new list and adds the passed values, if any, to the list +func New(values ...interface{}) *ArrayList { + list := &ArrayList{} + if len(values) > 0 { + list.Add(values...) } - - l.headIndex = l.reserveHead - l.nextIndex = l.headIndex - - l.data = make([]interface{}, newsize, newsize) + return list } -// Add add value to the tail of list -func (l *ArrayList) Add(v interface{}) { - - if l.nextIndex >= uint(len(l.data)) { - l.grow() +// Add appends a value at the end of the list +func (list *ArrayList) Add(values ...interface{}) { + list.growBy(len(values)) + for _, value := range values { + list.data[list.size] = value + list.size++ } - - l.size++ - l.data[l.nextIndex] = v - // grow } -// Push push is equal to add -func (l *ArrayList) Push(v interface{}) { - l.data = append(l.data, v) -} +// 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 *ArrayList) Get(index int) (interface{}, bool) { -func (l *ArrayList) Set(idx uint, value interface{}) { - l.data[idx] = value -} - -func (l *ArrayList) Get(idx uint) (result interface{}, isfound bool) { - if idx >= l.Size() { - return nil, false - } - return l.data[idx], true -} - -func (l *ArrayList) Pop() (result interface{}, found bool) { - if l.Size() == 0 { - return nil, false - } - rindex := len(l.data) - 1 - result = l.data[rindex] - l.data = l.data[0:rindex] - return result, true -} - -func (l *ArrayList) Remove(idx uint) (rvalue interface{}, isfound bool) { - - if idx >= l.Size() { + if !list.withinRange(index) { return nil, false } - rvalue = l.data[idx] - l.data = append(l.data[0:idx], l.data[idx+1:]) - - return rvalue, true + return list.data[index], true } -func (l *ArrayList) Values() (result []interface{}) { - values := make([]interface{}, l.Size(), l.Size()) - copy(values, l.data) - return values +// Remove removes the element at the given index from the list. +func (list *ArrayList) Remove(index int) { + + if !list.withinRange(index) { + return + } + + list.data[index] = nil // cleanup reference + copy(list.data[index:], list.data[index+1:list.size]) // shift to the left by one (slow operation, need ways to optimize this) + list.size-- + + list.shrink() } -func (l *ArrayList) Traversal(every func(index int, cur interface{}) bool) { - for i, cur := range l.data { - if !every(i, cur) { - return +// 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. +func (list *ArrayList) Contains(values ...interface{}) bool { + + for _, searchValue := range values { + found := false + for _, element := range list.data { + if element == searchValue { + found = true + break + } + } + if !found { + return false } } + return true +} + +// Values returns all elements in the list. +func (list *ArrayList) Values() []interface{} { + newElements := make([]interface{}, list.size, list.size) + copy(newElements, list.data[:list.size]) + return newElements +} + +//IndexOf returns index of provided element +func (list *ArrayList) IndexOf(value interface{}) int { + if list.size == 0 { + return -1 + } + for index, element := range list.data { + if element == value { + return index + } + } + return -1 +} + +// Empty returns true if list does not contain any elements. +func (list *ArrayList) Empty() bool { + return list.size == 0 +} + +// Size returns number of elements within the list. +func (list *ArrayList) Size() int { + return list.size +} + +// Clear removes all elements from the list. +func (list *ArrayList) Clear() { + list.size = 0 + list.data = []interface{}{} +} + +// Sort sorts values (in-place) using. +func (list *ArrayList) Sort(comparator utils.Comparator) { + if len(list.data) < 2 { + return + } + utils.Sort(list.data[:list.size], comparator) +} + +// Swap swaps the two values at the specified positions. +func (list *ArrayList) Swap(i, j int) { + if list.withinRange(i) && list.withinRange(j) { + list.data[i], list.data[j] = list.data[j], list.data[i] + } +} + +// 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 *ArrayList) Insert(index int, values ...interface{}) { + + if !list.withinRange(index) { + // Append + if index == list.size { + list.Add(values...) + } + return + } + + l := len(values) + list.growBy(l) + list.size += l + copy(list.data[index+l:], list.data[index:list.size-l]) + copy(list.data[index:], values) +} + +// Set the value at specified index +// 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 *ArrayList) Set(index int, value interface{}) { + + if !list.withinRange(index) { + // Append + if index == list.size { + list.Add(value) + } + return + } + + list.data[index] = value +} + +// String returns a string representation of container +func (list *ArrayList) String() string { + str := "ArrayList\n" + values := []string{} + for _, value := range list.data[:list.size] { + values = append(values, fmt.Sprintf("%v", value)) + } + str += strings.Join(values, ", ") + return str +} + +// Check that the index is within bounds of the list +func (list *ArrayList) withinRange(index int) bool { + return index >= 0 && index < list.size +} + +func (list *ArrayList) resize(cap int) { + newElements := make([]interface{}, cap, cap) + copy(newElements, list.data) + list.data = newElements +} + +// Expand the array if necessary, i.e. capacity will be reached if we add n elements +func (list *ArrayList) growBy(n int) { + // When capacity is reached, grow by a factor of growthFactor and add number of elements + currentCapacity := cap(list.data) + if list.size+n >= currentCapacity { + newCapacity := int(growthFactor * float32(currentCapacity+n)) + list.resize(newCapacity) + } +} + +// Shrink the array if necessary, i.e. when size is shrinkFactor percent of current capacity +func (list *ArrayList) shrink() { + if shrinkFactor == 0.0 { + return + } + // Shrink when size is at shrinkFactor * capacity + currentCapacity := cap(list.data) + if list.size <= int(float32(currentCapacity)*shrinkFactor) { + list.resize(list.size) + } } diff --git a/list/linkedlist/linkedlist.go b/list/linkedlist/linkedlist.go index b88587c..d548df3 100644 --- a/list/linkedlist/linkedlist.go +++ b/list/linkedlist/linkedlist.go @@ -1,6 +1,9 @@ package linkedlist +import "fmt" + type Node struct { + prev *Node next *Node value interface{} } @@ -11,97 +14,228 @@ func (node *Node) Value() interface{} { type LinkedList struct { head *Node + tail *Node size uint } +// var nodePool *sync.Pool = &sync.Pool{ +// New: func() interface{} { +// return &Node{} +// }, +// } + func New() *LinkedList { - return &LinkedList{} + l := &LinkedList{} + l.head = &Node{} + l.head.prev = nil + + l.tail = &Node{} + l.tail.next = nil + + l.head.next = l.tail + l.tail.prev = l.head + return l } func (l *LinkedList) Size() uint { return l.size } -func (l *LinkedList) Push(v interface{}) { - l.size++ - if l.head == nil { - l.head = &Node{value: v} - return +func (l *LinkedList) PushFront(values ...interface{}) { + + var node *Node + l.size += uint(len(values)) + for _, v := range values { + node = &Node{} + node.value = v + + hnext := l.head.next + hnext.prev = node + + node.next = hnext + node.prev = l.head + l.head.next = node } - l.head = &Node{value: v, next: l.head} } -func (l *LinkedList) PushNode(n *Node) { - l.size++ - if l.head == nil { - l.head = n - return - } +func (l *LinkedList) PushBack(values ...interface{}) { - n.next = l.head - l.head = n + var node *Node + l.size += uint(len(values)) + for _, v := range values { + node = &Node{} + node.value = v + + tprev := l.tail.prev + tprev.next = node + + node.prev = tprev + node.next = l.tail + l.tail.prev = node + } } -func (l *LinkedList) Pop() (result interface{}, found bool) { - if n, ok := l.PopNode(); ok { - return n.value, ok +func (l *LinkedList) PopFront() (result interface{}, found bool) { + if l.size != 0 { + l.size-- + + temp := l.head.next + hnext := temp.next + hnext.prev = l.head + l.head.next = hnext + + result = temp.value + found = true + return } return nil, false } -func (l *LinkedList) PopNode() (result *Node, found bool) { - if l.head == nil { - return nil, false +func (l *LinkedList) PopBack() (result interface{}, found bool) { + if l.size != 0 { + l.size-- + + temp := l.tail.prev + tprev := temp.prev + tprev.next = l.tail + l.tail.prev = tprev + + result = temp.value + found = true + return + } + return nil, false +} + +func (l *LinkedList) Front() (result interface{}, found bool) { + if l.size != 0 { + return l.head.next.value, true + } + return nil, false +} + +func (l *LinkedList) Back() (result interface{}, found bool) { + if l.size != 0 { + return l.tail.prev.value, true + } + return nil, false +} + +func (l *LinkedList) Insert(idx uint, values ...interface{}) { + if idx > l.size { + return + } + + if idx > l.size/2 { + idx = l.size - idx + // 尾部 + for cur := l.tail.prev; cur != nil; cur = cur.prev { + + if idx == 0 { + + var start *Node + var end *Node + + start = &Node{value: values[0]} + end = start + + for _, value := range values[1:] { + node := &Node{value: value} + end.next = node + node.prev = end + end = node + } + + cnext := cur.next + + cur.next = start + start.prev = cur + + end.next = cnext + cnext.prev = end + + break + } + + idx-- + } + + } else { + // 头部 + for cur := l.head.next; cur != nil; cur = cur.next { + if idx == 0 { + + var start *Node + var end *Node + + start = &Node{value: values[0]} + end = start + + for _, value := range values[1:] { + node := &Node{value: value} + end.next = node + node.prev = end + end = node + } + + cprev := cur.prev + + cprev.next = start + start.prev = cprev + + end.next = cur + cur.prev = end + + break + } + + idx-- + } + } + + l.size += uint(len(values)) +} + +func (l *LinkedList) Remove(idx uint) { + if idx >= l.size { + panic(fmt.Sprintf("out of list range, size is %d, idx is %d", l.size, idx)) + } + if l.head != nil { + if idx == 0 { + l.size-- + temp := l.head + l.head = l.head.next + nodePool.Put(temp) + return + } + + for cur := l.head; cur.next != nil; cur = cur.next { + if idx == 1 { + l.size-- + result := cur.next + cur.next = result.next + result.next = nil + nodePool.Put(result) + return + } + idx-- + } } - result = l.head - found = true - l.head = result.next - result.next = nil - l.size-- return } -func (l *LinkedList) Remove(idx uint) (result *Node, found bool) { - if l.size == 0 { - return nil, false - } - - if idx == 0 { - result = l.head - found = true - l.head = result.next - result.next = nil - l.size-- - return - } - - for cur := l.head; cur.next != nil; cur = cur.next { - if idx == 1 { - l.size-- - result = cur.next - found = true - cur.next = result.next - result.next = nil - return - } - idx-- - } - - return nil, false -} - func (l *LinkedList) Values() (result []interface{}) { - l.Traversal(func(cur *Node) bool { - result = append(result, cur.value) + l.Traversal(func(value interface{}) bool { + result = append(result, value) return true }) return } -func (l *LinkedList) Traversal(every func(*Node) bool) { - for cur := l.head; cur != nil; cur = cur.next { - if !every(cur) { +func (l *LinkedList) Traversal(every func(interface{}) bool) { + for cur := l.head.next; cur != l.tail; cur = cur.next { + if !every(cur.value) { break } } diff --git a/list/linkedlist/linkedlist_test.go b/list/linkedlist/linkedlist_test.go index 9d89c7e..79286cc 100644 --- a/list/linkedlist/linkedlist_test.go +++ b/list/linkedlist/linkedlist_test.go @@ -3,13 +3,14 @@ package linkedlist import ( "testing" + "github.com/Pallinder/go-randomdata" "github.com/davecgh/go-spew/spew" ) -func TestPush(t *testing.T) { +func TestPushFront(t *testing.T) { l := New() for i := 0; i < 5; i++ { - l.Push(i) + l.PushFront(i) } var result string result = spew.Sprint(l.Values()) @@ -17,71 +18,219 @@ func TestPush(t *testing.T) { t.Error(result) } - l.Push(0) + l.PushFront(0) result = spew.Sprint(l.Values()) if result != "[0 4 3 2 1 0]" { t.Error(result) } } -func TestPop(t *testing.T) { +func TestPushBack(t *testing.T) { l := New() for i := 0; i < 5; i++ { - l.Push(i) + l.PushBack(i) } - - if v, ok := l.Pop(); ok { - if v != 4 { - t.Error(v) - } - } else { - t.Error("Pop should ok, but is not ok") - } - var result string result = spew.Sprint(l.Values()) - if result != "[3 2 1 0]" { + if result != "[0 1 2 3 4]" { t.Error(result) } - for i := 3; l.Size() != 0; i-- { - if v, ok := l.Pop(); ok { - if v != i { - t.Error(i, v, "is not equals") - } - } else { - t.Error("Pop should ok, but is not ok", i) - } - } - - l.Push(0) + l.PushBack(0) result = spew.Sprint(l.Values()) - if result != "[0]" { + if result != "[0 1 2 3 4 0]" { t.Error(result) } - - if l.Size() != 1 { - t.Error("l.Size() == 1, but is error, size = ", l.Size()) - } } -func TestRemove(t *testing.T) { +func TestPopFront(t *testing.T) { l := New() + // "[0 1 2 3 4]" for i := 0; i < 5; i++ { - l.Push(i) + l.PushFront(i) } + // var result string - for i := 0; i < 5; i++ { - if n, ok := l.Remove(0); ok { - if n.Value() != 4-i { - t.Error(n) + for i := 4; i >= 0; i-- { + if v, ok := l.PopFront(); ok { + if v != i { + t.Error("[4 3 2 1 0] PopFront value should be ", i, ", but is ", v) } } else { - t.Error("Pop should ok, but is not ok", i) + t.Error("PopFront is not ok") + } + + if l.Size() != uint(i) { + t.Error("l.Size() is error, is", l.Size()) + } + } +} + +func TestPopBack(t *testing.T) { + l := New() + // "[0 1 2 3 4]" + for i := 0; i < 5; i++ { + l.PushFront(i) + } + // var result string + + for i := 0; i < 5; i++ { + if v, ok := l.PopBack(); ok { + if v != i { + t.Error("[4 3 2 1 0] PopFront value should be ", i, ", but is ", v) + } + } else { + t.Error("PopFront is not ok") + } + + if l.Size() != uint(5-i-1) { + t.Error("l.Size() is error, is", l.Size()) } } - if l.Size() != 0 { - t.Error("l.Size() == 0, but is error, size = ", l.Size()) +} + +func TestInsert(t *testing.T) { + l1 := New() + l2 := New() + // "[4 3 2 1 0]" + for i := 0; i < 5; i++ { + l1.Insert(0, i) + l2.PushFront(i) + } + + var result1, result2 string + result1 = spew.Sprint(l1.Values()) + result2 = spew.Sprint(l2.Values()) + if result1 != result2 { + t.Error(result1, result2) + } + + for i := 0; i < 5; i++ { + l1.Insert(l1.Size(), i) + l2.PushBack(i) + // t.Error(l1.Values(), l2.Values()) + } + + result1 = spew.Sprint(l1.Values()) + result2 = spew.Sprint(l2.Values()) + if result1 != result2 { + t.Error(result1, result2) + } + + if result1 != "[4 3 2 1 0 0 1 2 3 4]" { + t.Error("result should be [4 3 2 1 0 0 1 2 3 4]\n but result is", result1) + } + + l1.Insert(1, 99) + result1 = spew.Sprint(l1.Values()) + if result1 != "[4 99 3 2 1 0 0 1 2 3 4]" { + t.Error("[4 3 2 1 0 0 1 2 3 4] insert with index 1, should be [4 99 3 2 1 0 0 1 2 3 4]\n but result is", result1) } } + +func BenchmarkPushBack(b *testing.B) { + + ec := 5 + cs := 2000000 + b.N = cs * ec + + for c := 0; c < ec; c++ { + l := New() + for i := 0; i < cs; i++ { + l.PushBack(i) + } + } +} + +func BenchmarkPushFront(b *testing.B) { + + ec := 5 + cs := 2000000 + b.N = cs * ec + + for c := 0; c < ec; c++ { + l := New() + for i := 0; i < cs; i++ { + l.PushFront(i) + } + } + +} + +func BenchmarkInsert(b *testing.B) { + + ec := 10 + cs := 1000 + b.N = cs * ec + + for c := 0; c < ec; c++ { + l := New() + for i := 0; i < cs; i++ { + ridx := randomdata.Number(0, int(l.Size())+1) + l.Insert(uint(ridx), i) + } + } +} + +// func TestPop(t *testing.T) { +// l := New() +// for i := 0; i < 5; i++ { +// l.Push(i) +// } + +// if v, ok := l.Pop(); ok { +// if v != 4 { +// t.Error(v) +// } +// } else { +// t.Error("Pop should ok, but is not ok") +// } + +// var result string +// result = spew.Sprint(l.Values()) +// if result != "[3 2 1 0]" { +// t.Error(result) +// } + +// for i := 3; l.Size() != 0; i-- { +// if v, ok := l.Pop(); ok { +// if v != i { +// t.Error(i, v, "is not equals") +// } +// } else { +// t.Error("Pop should ok, but is not ok", i) +// } +// } + +// l.Push(0) +// result = spew.Sprint(l.Values()) +// if result != "[0]" { +// t.Error(result) +// } + +// if l.Size() != 1 { +// t.Error("l.Size() == 1, but is error, size = ", l.Size()) +// } +// } + +// func TestRemove(t *testing.T) { +// l := New() +// for i := 0; i < 5; i++ { +// l.Push(i) +// } + +// for i := 0; i < 5; i++ { +// l.Remove(0) +// if l.head != nil { +// if l.head.Value() != 4-i-1 { +// t.Error("l.head is error") +// } +// } +// t.Error(l.Size()) +// } + +// if l.Size() != 0 { +// t.Error("l.Size() == 0, but is error, size = ", l.Size()) +// } +// }