This commit is contained in:
huangsimin 2019-05-22 17:52:50 +08:00
parent 2b79a1acab
commit 60089c905a
4 changed files with 323 additions and 281 deletions

View File

@ -1,218 +1,302 @@
package arraylist package arraylist
import ( import "log"
"fmt"
"strings"
"github.com/emirpasic/gods/lists"
"github.com/emirpasic/gods/utils"
)
func assertListImplementation() {
var _ lists.List = (*ArrayList)(nil)
}
type ArrayList struct { type ArrayList struct {
data []interface{} data []interface{}
size int hidx uint
tidx uint
size uint
growSizePoint uint
} }
const ( const (
listLimit = uint(1) << 63
initCap = uint(8)
growthFactor = float32(2.0) // growth by 100% growthFactor = float32(2.0) // growth by 100%
shrinkFactor = float32(0.25) // shrink when size is 25% of capacity (0 means never shrink) shrinkFactor = float32(0.25) // shrink when size is 25% of capacity (0 means never shrink)
) )
// New instantiates a new list and adds the passed values, if any, to the list // New instantiates a new list and adds the passed values, if any, to the list
func New(values ...interface{}) *ArrayList { func New() *ArrayList {
list := &ArrayList{} l := &ArrayList{}
if len(values) > 0 { l.data = make([]interface{}, initCap, initCap)
list.Add(values...) l.tidx = initCap / 2
} l.hidx = l.tidx - 1
return list return l
} }
// Add appends a value at the end of the list func (l *ArrayList) Clear() {
func (list *ArrayList) Add(values ...interface{}) { l.data = make([]interface{}, 8, 8)
list.growBy(len(values)) l.tidx = initCap / 2
for _, value := range values { l.hidx = l.tidx - 1
list.data[list.size] = value l.size = 0
list.size++ }
func (l *ArrayList) Empty() bool {
return l.size == 0
}
func (l *ArrayList) Size() uint {
return l.size
}
func (l *ArrayList) shrink() {
}
// 后续需要优化 growth 策略
func (l *ArrayList) growth(flag int) {
if l.size >= listLimit {
log.Panic("list size is over limit", listLimit)
}
switch flag {
case -1:
growthsize := l.size << 1
temp := make([]interface{}, growthsize, growthsize)
ghidx := l.size / 2
gtidx := ghidx + l.size + 1
copy(temp[ghidx+1:], l.data[l.hidx+1:l.tidx])
l.data = temp
l.hidx = ghidx
l.tidx = gtidx
case 1:
growthsize := l.size << 1
temp := make([]interface{}, growthsize, growthsize)
ghidx := l.size / 2
gtidx := ghidx + l.size + 1
copy(temp[ghidx+1:], l.data[l.hidx+1:l.tidx])
l.data = temp
l.hidx = ghidx
l.tidx = gtidx
case 0:
growthsize := l.size << 1
temp := make([]interface{}, growthsize, growthsize)
ghidx := l.size / 2
gtidx := ghidx + l.size + 1
copy(temp[ghidx+1:], l.data[l.hidx+1:l.tidx])
l.data = temp
l.hidx = ghidx
l.tidx = gtidx
} }
} }
// Get returns the element at index. func (l *ArrayList) PushFront(values ...interface{}) {
// Second return parameter is true if index is within bounds of the array and array is not empty, otherwise false. psize := uint(len(values))
func (list *ArrayList) Get(index int) (interface{}, bool) { if l.hidx+1-psize > listLimit {
l.growth(-1)
// panic("growth -1")
}
if !list.withinRange(index) { for _, v := range values {
l.data[l.hidx] = v
l.hidx--
}
l.size += psize
}
func (l *ArrayList) PushBack(values ...interface{}) {
psize := uint(len(values))
if l.tidx+psize >= uint(len(l.data)) {
l.growth(1)
}
for _, v := range values {
l.data[l.tidx] = v
l.tidx++
}
l.size += psize
}
func (l *ArrayList) PopFront() (result interface{}, found bool) {
if l.size != 0 {
l.size--
l.hidx++
return l.data[l.hidx], true
}
return nil, false return nil, false
} }
return list.data[index], true func (l *ArrayList) PopBack() (result interface{}, found bool) {
if l.size != 0 {
l.size--
l.tidx--
return l.data[l.tidx], true
}
return nil, false
} }
// Remove removes the element at the given index from the list. func (l *ArrayList) Index(idx uint) (interface{}, bool) {
func (list *ArrayList) Remove(index int) { if idx < l.size {
return l.data[idx+l.hidx+1], true
}
return nil, false
}
func (l *ArrayList) Remove(idx uint) (result interface{}, isfound bool) {
if idx < l.size {
return nil, false
}
offset := l.hidx + 1 + idx
isfound = true
result = l.data[offset]
l.data[offset] = nil // cleanup reference
copy(l.data[offset:], l.data[idx+1:l.size]) // shift to the left by one (slow operation, need ways to optimize this)
l.size--
l.shrink()
if !list.withinRange(index) {
return return
} }
list.data[index] = nil // cleanup reference // func (list *ArrayList) Contains(values ...interface{}) bool {
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() // for _, searchValue := range values {
} // found := false
// for _, element := range list.data {
// if element == searchValue {
// found = true
// break
// }
// }
// if !found {
// return false
// }
// }
// return true
// }
// Contains checks if elements (one or more) are present in the set. func (l *ArrayList) Values() []interface{} {
// All elements have to be present in the set for the method to return true. newElements := make([]interface{}, l.size, l.size)
// Performance time complexity of n^2. copy(newElements, l.data[l.hidx+1:l.tidx])
// 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 return newElements
} }
//IndexOf returns index of provided element // func (list *ArrayList) IndexOf(value interface{}) int {
func (list *ArrayList) IndexOf(value interface{}) int { // if list.size == 0 {
if list.size == 0 { // return -1
return -1 // }
} // for index, element := range list.data {
for index, element := range list.data { // if element == value {
if element == value { // return index
return index // }
} // }
} // return -1
return -1 // }
}
// Empty returns true if list does not contain any elements. // func (list *ArrayList) Empty() bool {
func (list *ArrayList) Empty() bool { // return list.size == 0
return list.size == 0 // }
}
// Size returns number of elements within the list. // func (list *ArrayList) Size() int {
func (list *ArrayList) Size() int { // return list.size
return list.size // }
}
// Clear removes all elements from the list. // // Clear removes all elements from the list.
func (list *ArrayList) Clear() { // func (list *ArrayList) Clear() {
list.size = 0 // list.size = 0
list.data = []interface{}{} // list.data = []interface{}{}
} // }
// Sort sorts values (in-place) using. // // Sort sorts values (in-place) using.
func (list *ArrayList) Sort(comparator utils.Comparator) { // func (list *ArrayList) Sort(comparator utils.Comparator) {
if len(list.data) < 2 { // if len(list.data) < 2 {
return // return
} // }
utils.Sort(list.data[:list.size], comparator) // utils.Sort(list.data[:list.size], comparator)
} // }
// Swap swaps the two values at the specified positions. // // Swap swaps the two values at the specified positions.
func (list *ArrayList) Swap(i, j int) { // func (list *ArrayList) Swap(i, j int) {
if list.withinRange(i) && list.withinRange(j) { // if list.withinRange(i) && list.withinRange(j) {
list.data[i], list.data[j] = list.data[j], list.data[i] // 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. // // 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 // // 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. // // Note: position equal to list's size is valid, i.e. append.
func (list *ArrayList) Insert(index int, values ...interface{}) { // func (list *ArrayList) Insert(index int, values ...interface{}) {
if !list.withinRange(index) { // if !list.withinRange(index) {
// Append // // Append
if index == list.size { // if index == list.size {
list.Add(values...) // list.Add(values...)
} // }
return // return
} // }
l := len(values) // l := len(values)
list.growBy(l) // list.growBy(l)
list.size += l // list.size += l
copy(list.data[index+l:], list.data[index:list.size-l]) // copy(list.data[index+l:], list.data[index:list.size-l])
copy(list.data[index:], values) // copy(list.data[index:], values)
} // }
// Set the value at specified index // // Set the value at specified index
// Does not do anything if position is negative or bigger than list's size // // 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. // // Note: position equal to list's size is valid, i.e. append.
func (list *ArrayList) Set(index int, value interface{}) { // func (list *ArrayList) Set(index int, value interface{}) {
if !list.withinRange(index) { // if !list.withinRange(index) {
// Append // // Append
if index == list.size { // if index == list.size {
list.Add(value) // list.Add(value)
} // }
return // return
} // }
list.data[index] = value // list.data[index] = value
} // }
// String returns a string representation of container // // String returns a string representation of container
func (list *ArrayList) String() string { // func (list *ArrayList) String() string {
str := "ArrayList\n" // str := "ArrayList\n"
values := []string{} // values := []string{}
for _, value := range list.data[:list.size] { // for _, value := range list.data[:list.size] {
values = append(values, fmt.Sprintf("%v", value)) // values = append(values, fmt.Sprintf("%v", value))
} // }
str += strings.Join(values, ", ") // str += strings.Join(values, ", ")
return str // return str
} // }
// Check that the index is within bounds of the list // // Check that the index is within bounds of the list
func (list *ArrayList) withinRange(index int) bool { // func (list *ArrayList) withinRange(index int) bool {
return index >= 0 && index < list.size // return index >= 0 && index < list.size
} // }
func (list *ArrayList) resize(cap int) { // func (list *ArrayList) resize(cap int) {
newElements := make([]interface{}, cap, cap) // newElements := make([]interface{}, cap, cap)
copy(newElements, list.data) // copy(newElements, list.data)
list.data = newElements // list.data = newElements
} // }
// Expand the array if necessary, i.e. capacity will be reached if we add n elements // // Expand the array if necessary, i.e. capacity will be reached if we add n elements
func (list *ArrayList) growBy(n int) { // func (list *ArrayList) growBy(n int) {
// When capacity is reached, grow by a factor of growthFactor and add number of elements // // When capacity is reached, grow by a factor of growthFactor and add number of elements
currentCapacity := cap(list.data) // currentCapacity := cap(list.data)
if list.size+n >= currentCapacity { // if list.size+n >= currentCapacity {
newCapacity := int(growthFactor * float32(currentCapacity+n)) // newCapacity := int(growthFactor * float32(currentCapacity+n))
list.resize(newCapacity) // list.resize(newCapacity)
} // }
} // }
// Shrink the array if necessary, i.e. when size is shrinkFactor percent of current capacity // // Shrink the array if necessary, i.e. when size is shrinkFactor percent of current capacity
func (list *ArrayList) shrink() { // func (list *ArrayList) shrink() {
if shrinkFactor == 0.0 { // if shrinkFactor == 0.0 {
return // return
} // }
// Shrink when size is at shrinkFactor * capacity // // Shrink when size is at shrinkFactor * capacity
currentCapacity := cap(list.data) // currentCapacity := cap(list.data)
if list.size <= int(float32(currentCapacity)*shrinkFactor) { // if list.size <= int(float32(currentCapacity)*shrinkFactor) {
list.resize(list.size) // list.resize(list.size)
} // }
} // }

View File

@ -8,80 +8,90 @@ import (
func TestPush(t *testing.T) { func TestPush(t *testing.T) {
l := New() l := New()
for i := 0; i < 5; i++ { for i := 0; i < 2; i++ {
l.Push(i) l.PushFront(1)
} }
var result string var result string
result = spew.Sprint(l.Values()) result = spew.Sprint(l.Values())
if result != "[4 3 2 1 0]" { if result != "[1 1]" {
t.Error(result) t.Error(result)
} }
l.Push(0) for i := 0; i < 2; i++ {
l.PushBack(2)
}
result = spew.Sprint(l.Values()) result = spew.Sprint(l.Values())
if result != "[0 4 3 2 1 0]" { if result != "[1 1 2 2]" {
t.Error(result) t.Error(result)
} }
} }
func TestGrowth(t *testing.T) {
l := New()
for i := 0; i < 5; i++ {
l.PushFront(1)
}
var result string
result = spew.Sprint(l.Values())
if result != "[1 1]" {
t.Error(result)
}
l = New()
for i := 0; i < 7; i++ {
l.PushBack(1)
}
result = spew.Sprint(l.Values())
if result != "[1 1]" {
t.Error(result)
}
// for i := 0; i < 2; i++ {
// l.PushBack(2)
// }
// result = spew.Sprint(l.Values())
// if result != "[1 1 2 2]" {
// t.Error(result)
// }
}
func TestPop(t *testing.T) { func TestPop(t *testing.T) {
l := New() l := New()
for i := 0; i < 5; i++ { for i := 0; i < 5; i++ {
l.Push(i) l.PushFront(i)
} }
if v, ok := l.Pop(); ok { for i := 4; i >= 0; i-- {
if v != 4 { if v, ok := l.PopFront(); ok {
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 { if v != i {
t.Error(i, v, "is not equals") t.Error("should be ", v)
} }
} else { } else {
t.Error("Pop should ok, but is not ok", i) t.Error("should be ok, value is", v)
} }
} }
l.Push(0) if v, ok := l.PopFront(); ok {
result = spew.Sprint(l.Values()) t.Error("should not be ok, v = ", v)
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++ { for i := 0; i < 5; i++ {
if n, ok := l.Remove(0); ok { l.PushFront(i)
if n != 4-i { }
t.Error(n)
for i := 0; i < 5; i++ {
if v, ok := l.PopBack(); ok {
if v != i {
t.Error("should be ", v)
} }
} else { } else {
t.Error("Pop should ok, but is not ok", i) t.Error("should be ok, value is", v)
} }
} }
if l.Size() != 0 { if v, ok := l.PopBack(); ok {
t.Error("l.Size() == 0, but is error, size = ", l.Size()) t.Error("should not be ok, v = ", v)
} }
} }

View File

@ -37,6 +37,16 @@ func New() *LinkedList {
return l return l
} }
func (l *LinkedList) Clear() {
l.head.next = nil
l.tail.prev = nil
l.size = 0
}
func (l *LinkedList) Empty() bool {
return l.size == 0
}
func (l *LinkedList) Size() uint { func (l *LinkedList) Size() uint {
return l.size return l.size
} }

View File

@ -507,65 +507,3 @@ func BenchmarkInsert(b *testing.B) {
} }
} }
} }
// 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())
// }
// }