Compare commits

..

No commits in common. "develop" and "feature/todo-trie" have entirely different histories.

44 changed files with 85 additions and 5724 deletions

View File

@ -15,7 +15,7 @@ import (
)
func main() {
pq := New(compare.Int)
pq := pqueuekey.New(compare.Int)
pq.Push(1, 1)
pq.Push(4, 4)
pq.Push(5, 5)
@ -40,15 +40,14 @@ func main() {
log.Println(values3)
iter := pq.Iterator() // Next 大到小 从root节点起始
log.Println(pq.String())
// log.Println(iter.Value()) 直接使用会报错,
iter.ToHead()
iter.Next()
log.Println(iter.Value()) // 起始最大值. true 5
log.Println(iter.Value()) // 起始最大值. true 5
log.Println(iter.Prev(), iter.Value()) // false 5
// Prev 大到小
log.Println(iter.Next(), iter.Value()) // true 4
}
```

1
TODO
View File

@ -1 +0,0 @@
add iterator test every file

View File

@ -8,84 +8,6 @@ import "time"
// k1 < k2 --> -1
type Compare func(k1, k2 interface{}) int
// RuneArray []rune compare
func RuneArray(k1, k2 interface{}) int {
s1 := k1.([]rune)
s2 := k2.([]rune)
switch {
case len(s1) > len(s2):
for i := 0; i < len(s2); i++ {
if s1[i] != s2[i] {
if s1[i] > s2[i] {
return 1
}
return -1
}
}
return 1
case len(s1) < len(s2):
for i := 0; i < len(s1); i++ {
if s1[i] != s2[i] {
if s1[i] > s2[i] {
return 1
}
return -1
}
}
return -1
default:
for i := 0; i < len(s1); i++ {
if s1[i] != s2[i] {
if s1[i] > s2[i] {
return 1
}
return -1
}
}
return 0
}
}
// ByteArray []byte compare
func ByteArray(k1, k2 interface{}) int {
s1 := k1.([]byte)
s2 := k2.([]byte)
switch {
case len(s1) > len(s2):
for i := 0; i < len(s2); i++ {
if s1[i] != s2[i] {
if s1[i] > s2[i] {
return 1
}
return -1
}
}
return 1
case len(s1) < len(s2):
for i := 0; i < len(s1); i++ {
if s1[i] != s2[i] {
if s1[i] > s2[i] {
return 1
}
return -1
}
}
return -1
default:
for i := 0; i < len(s1); i++ {
if s1[i] != s2[i] {
if s1[i] > s2[i] {
return 1
}
return -1
}
}
return 0
}
}
// String comp
func String(k1, k2 interface{}) int {
s1 := k1.(string)

1
go.mod
View File

@ -5,4 +5,5 @@ 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
)

1
go.sum
View File

@ -4,4 +4,3 @@ 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=
github.com/petar/GoLLRB v0.0.0-20190514000832-33fb24c13b99 h1:KcEvVBAvyHkUdFAygKAzwB6LAcZ6LS32WHmRD2VyXMI=

View File

@ -1,7 +1,7 @@
package pqueue
import (
lastack "github.com/474420502/focus/stack/listarraystack"
"github.com/474420502/focus/stack/listarraystack"
)
type Iterator struct {
@ -31,36 +31,13 @@ func NewIteratorWithCap(n *Node, cap int) *Iterator {
}
func (iter *Iterator) ToHead() {
if iter.cur == nil {
iter.cur = iter.up
for iter.Prev() {
}
for iter.cur.parent != nil {
iter.cur = iter.cur.parent
}
for iter.cur.children[1] != nil {
iter.cur = iter.cur.children[1]
}
iter.SetNode(iter.cur)
iter.cur = nil
}
func (iter *Iterator) ToTail() {
if iter.cur == nil {
iter.cur = iter.up
for iter.Next() {
}
for iter.cur.parent != nil {
iter.cur = iter.cur.parent
}
for iter.cur.children[0] != nil {
iter.cur = iter.cur.children[0]
}
iter.SetNode(iter.cur)
iter.cur = nil
}
func (iter *Iterator) GetNode() *Node {

View File

@ -50,20 +50,20 @@ func (pq *PriorityQueue) IndexNode(idx int) (*Node, bool) {
return n, n != nil
}
func (pq *PriorityQueue) Get(value interface{}) (interface{}, bool) {
return pq.queue.Get(value)
func (pq *PriorityQueue) Get(key interface{}) (interface{}, bool) {
return pq.queue.Get(key)
}
func (pq *PriorityQueue) GetNode(value interface{}) (*Node, bool) {
return pq.queue.GetNode(value)
func (pq *PriorityQueue) GetNode(key interface{}) (*Node, bool) {
return pq.queue.GetNode(key)
}
func (pq *PriorityQueue) GetAround(value interface{}) [3]interface{} {
return pq.queue.GetAround(value)
func (pq *PriorityQueue) GetAround(key interface{}) [3]interface{} {
return pq.queue.GetAround(key)
}
func (pq *PriorityQueue) GetAroundNode(value interface{}) [3]*Node {
return pq.queue.getArounNode(value)
func (pq *PriorityQueue) GetAroundNode(key interface{}) [3]*Node {
return pq.queue.getArounNode(key)
}
func (pq *PriorityQueue) GetRange(k1, k2 interface{}) []interface{} {
@ -74,12 +74,8 @@ func (pq *PriorityQueue) RemoveIndex(idx int) (interface{}, bool) {
return pq.queue.RemoveIndex(idx)
}
func (pq *PriorityQueue) Remove(vlaue interface{}) (interface{}, bool) {
return pq.queue.Remove(vlaue)
}
func (pq *PriorityQueue) RemoveNode(node *Node) {
pq.queue.removeNode(node)
func (pq *PriorityQueue) Remove(key interface{}) (interface{}, bool) {
return pq.queue.Remove(key)
}
func (pq *PriorityQueue) Values() []interface{} {

View File

@ -170,28 +170,6 @@ func TestQueueRemove(t *testing.T) {
}
}
func TestQueueRemoveNode(t *testing.T) {
pq := New(compare.Int)
l := []int{32, 10, 53, 78, 90, 1, 4}
for _, v := range l {
pq.Push(v)
}
content := ""
for _, v := range l {
if n, ok := pq.GetNode(v); ok {
pq.RemoveNode(n)
content += spew.Sprint(pq.Values())
} else {
t.Error("can not get Node: ", v)
}
}
if content != "[90 78 53 10 4 1][90 78 53 4 1][90 78 4 1][90 4 1][4 1][4][]" {
t.Error(content)
}
}
func TestQueueRemoveIndex(t *testing.T) {
pq := New(compare.Int)
l := []int{32, 10, 53, 78, 90, 1, 4}
@ -283,15 +261,13 @@ func TestPriorityQueue_Iterator(t *testing.T) {
values := pq.Values()
for i := 0; ; i++ {
if !iter.Next() {
break
}
if values[i] != iter.Value() {
t.Error(values[i], " != ", iter.Value())
}
if !iter.Prev() {
break
}
}
}

View File

@ -1,7 +1,7 @@
package pqueuekey
import (
lastack "github.com/474420502/focus/stack/listarraystack"
"github.com/474420502/focus/stack/listarraystack"
)
type Iterator struct {
@ -31,36 +31,13 @@ func NewIteratorWithCap(n *Node, cap int) *Iterator {
}
func (iter *Iterator) ToHead() {
if iter.cur == nil {
iter.cur = iter.up
for iter.Prev() {
}
for iter.cur.parent != nil {
iter.cur = iter.cur.parent
}
for iter.cur.children[1] != nil {
iter.cur = iter.cur.children[1]
}
iter.SetNode(iter.cur)
iter.cur = nil
}
func (iter *Iterator) ToTail() {
if iter.cur == nil {
iter.cur = iter.up
for iter.Next() {
}
for iter.cur.parent != nil {
iter.cur = iter.cur.parent
}
for iter.cur.children[0] != nil {
iter.cur = iter.cur.children[0]
}
iter.SetNode(iter.cur)
iter.cur = nil
}
func (iter *Iterator) GetNode() *Node {
@ -73,10 +50,6 @@ func (iter *Iterator) SetNode(n *Node) {
iter.tstack.Clear()
}
func (iter *Iterator) Key() interface{} {
return iter.cur.key
}
func (iter *Iterator) Value() interface{} {
return iter.cur.value
}

View File

@ -78,10 +78,6 @@ func (pq *PriorityQueue) Remove(key interface{}) (interface{}, bool) {
return pq.queue.Remove(key)
}
func (pq *PriorityQueue) RemoveNode(node *Node) {
pq.queue.removeNode(node)
}
func (pq *PriorityQueue) Values() []interface{} {
return pq.queue.Values()
}

View File

@ -170,28 +170,6 @@ func TestQueueRemove(t *testing.T) {
}
}
func TestQueueRemoveNode(t *testing.T) {
pq := New(compare.Int)
l := []int{32, 10, 53, 78, 90, 1, 4}
for _, v := range l {
pq.Push(v, v)
}
content := ""
for _, v := range l {
if n, ok := pq.GetNode(v); ok {
pq.RemoveNode(n)
content += spew.Sprint(pq.Values())
} else {
t.Error("can not get Node: ", v)
}
}
if content != "[90 78 53 10 4 1][90 78 53 4 1][90 78 4 1][90 4 1][4 1][4][]" {
t.Error(content)
}
}
func TestQueueRemoveIndex(t *testing.T) {
pq := New(compare.Int)
l := []int{32, 10, 53, 78, 90, 1, 4}
@ -387,15 +365,13 @@ func TestPriorityQueue_Iterator(t *testing.T) {
values := pq.Values()
for i := 0; ; i++ {
if !iter.Next() {
break
}
if values[i] != iter.Value() {
t.Error(values[i], " != ", iter.Value())
}
if !iter.Next() {
break
}
}
}
@ -483,10 +459,10 @@ func TestMain(t *testing.T) {
log.Println(pq.String())
// log.Println(iter.Value()) 直接使用会报错,
iter.ToHead()
iter.Next()
log.Println(iter.Value()) // 起始最大值. true 5
log.Println(iter.Prev(), iter.Value()) // false 5
// Prev 大到小
log.Println(iter.Next(), iter.Value()) // true 4
}

View File

@ -152,14 +152,7 @@ func TestTreeSet_Iterator(t *testing.T) {
iter := set.Iterator()
iter.ToHead()
// if not call Next Prev will error
// 5 4 3
// if iter.Value() != nil {
// t.Error(iter.Value())
// }
iter.Next()
// 3 4 5
if iter.Value() != 3 {
t.Error(iter.Value())
}
@ -169,8 +162,12 @@ func TestTreeSet_Iterator(t *testing.T) {
t.Error(iter.Value())
}
iter.Next()
if iter.Value() != 5 {
t.Error(iter.Value())
}
iter.ToTail()
iter.Prev()
if iter.Value() != 5 {
t.Error(iter.Value())
}
@ -179,16 +176,4 @@ func TestTreeSet_Iterator(t *testing.T) {
if iter.Value() != 4 {
t.Error(iter.Value())
}
iter.ToHead()
iter.Prev()
if iter.Value() != 3 {
t.Error(iter.Value())
}
iter.ToTail()
iter.Next()
if iter.Value() != 5 {
t.Error(iter.Value())
}
}

View File

@ -49,13 +49,11 @@ func TestIteratorHeadTail(t *testing.T) {
}
iter.ToHead()
iter.Prev() // or iter.Next
if iter.Value() != 1 {
t.Error("iter.Value() != ", 14, " value =", iter.Value())
}
iter.ToTail()
iter.Next() // or iter.Prev()
if iter.Value() != 30 {
t.Error("iter.Value() != ", 30, " value =", iter.Value())
}

View File

@ -1,7 +1,7 @@
package avl
import (
lastack "github.com/474420502/focus/stack/listarraystack"
"github.com/474420502/focus/stack/listarraystack"
)
type Iterator struct {
@ -31,36 +31,13 @@ func NewIteratorWithCap(n *Node, cap int) *Iterator {
}
func (iter *Iterator) ToHead() {
if iter.cur == nil {
iter.cur = iter.up
for iter.Prev() {
}
for iter.cur.parent != nil {
iter.cur = iter.cur.parent
}
for iter.cur.children[0] != nil {
iter.cur = iter.cur.children[0]
}
iter.SetNode(iter.cur)
iter.cur = nil
}
func (iter *Iterator) ToTail() {
if iter.cur == nil {
iter.cur = iter.up
for iter.Next() {
}
for iter.cur.parent != nil {
iter.cur = iter.cur.parent
}
for iter.cur.children[1] != nil {
iter.cur = iter.cur.children[1]
}
iter.SetNode(iter.cur)
iter.cur = nil
}
func (iter *Iterator) GetNode() *Node {

View File

@ -1,35 +0,0 @@
package avl
import (
"sort"
"testing"
"github.com/474420502/focus/compare"
)
func TestIerator(t *testing.T) {
tree := New(compare.Int)
l := []int{5, 10, 100, 30, 40, 70, 45, 35, 23}
for _, v := range l {
tree.Put(v)
}
sort.Ints(l)
iter := tree.Iterator()
iter.ToHead()
for i := 0; iter.Next(); i++ {
if iter.Value() != l[i] {
t.Error(iter.Value(), l[i])
}
}
iter.ToTail()
iter.Prev()
for i := len(l) - 1; iter.Next(); i-- {
if iter.Value() != l[i] {
t.Error(iter.Value(), l[i])
}
}
}

View File

@ -1,7 +1,7 @@
package avldup
import (
lastack "github.com/474420502/focus/stack/listarraystack"
"github.com/474420502/focus/stack/listarraystack"
)
type Iterator struct {
@ -31,36 +31,13 @@ func NewIteratorWithCap(n *Node, cap int) *Iterator {
}
func (iter *Iterator) ToHead() {
if iter.cur == nil {
iter.cur = iter.up
for iter.Prev() {
}
for iter.cur.parent != nil {
iter.cur = iter.cur.parent
}
for iter.cur.children[0] != nil {
iter.cur = iter.cur.children[0]
}
iter.SetNode(iter.cur)
iter.cur = nil
}
func (iter *Iterator) ToTail() {
if iter.cur == nil {
iter.cur = iter.up
for iter.Next() {
}
for iter.cur.parent != nil {
iter.cur = iter.cur.parent
}
for iter.cur.children[1] != nil {
iter.cur = iter.cur.children[1]
}
iter.SetNode(iter.cur)
iter.cur = nil
}
func (iter *Iterator) GetNode() *Node {

View File

@ -1,35 +0,0 @@
package avldup
import (
"sort"
"testing"
"github.com/474420502/focus/compare"
)
func TestIerator(t *testing.T) {
tree := New(compare.Int)
l := []int{5, 10, 100, 30, 40, 70, 45, 35, 23}
for _, v := range l {
tree.Put(v)
}
sort.Ints(l)
iter := tree.Iterator()
iter.ToHead()
for i := 0; iter.Next(); i++ {
if iter.Value() != l[i] {
t.Error(iter.Value(), l[i])
}
}
iter.ToTail()
iter.Prev()
for i := len(l) - 1; iter.Next(); i-- {
if iter.Value() != l[i] {
t.Error(iter.Value(), l[i])
}
}
}

View File

@ -1,7 +1,7 @@
package avlkey
import (
lastack "github.com/474420502/focus/stack/listarraystack"
"github.com/474420502/focus/stack/listarraystack"
)
type Iterator struct {
@ -31,36 +31,13 @@ func NewIteratorWithCap(n *Node, cap int) *Iterator {
}
func (iter *Iterator) ToHead() {
if iter.cur == nil {
iter.cur = iter.up
for iter.Prev() {
}
for iter.cur.parent != nil {
iter.cur = iter.cur.parent
}
for iter.cur.children[0] != nil {
iter.cur = iter.cur.children[0]
}
iter.SetNode(iter.cur)
iter.cur = nil
}
func (iter *Iterator) ToTail() {
if iter.cur == nil {
iter.cur = iter.up
for iter.Next() {
}
for iter.cur.parent != nil {
iter.cur = iter.cur.parent
}
for iter.cur.children[1] != nil {
iter.cur = iter.cur.children[1]
}
iter.SetNode(iter.cur)
iter.cur = nil
}
func (iter *Iterator) GetNode() *Node {
@ -73,10 +50,6 @@ func (iter *Iterator) SetNode(n *Node) {
iter.tstack.Clear()
}
func (iter *Iterator) Key() interface{} {
return iter.cur.key
}
func (iter *Iterator) Value() interface{} {
return iter.cur.value
}

View File

@ -1,35 +0,0 @@
package avlkey
import (
"sort"
"testing"
"github.com/474420502/focus/compare"
)
func TestIerator(t *testing.T) {
tree := New(compare.Int)
l := []int{5, 10, 100, 30, 40, 70, 45, 35, 23}
for _, v := range l {
tree.Put(v, v)
}
sort.Ints(l)
iter := tree.Iterator()
iter.ToHead()
for i := 0; iter.Next(); i++ {
if iter.Value() != l[i] {
t.Error(iter.Value(), l[i])
}
}
iter.ToTail()
iter.Prev()
for i := len(l) - 1; iter.Next(); i-- {
if iter.Value() != l[i] {
t.Error(iter.Value(), l[i])
}
}
}

View File

@ -1,7 +1,7 @@
package avlkeydup
import (
lastack "github.com/474420502/focus/stack/listarraystack"
"github.com/474420502/focus/stack/listarraystack"
)
type Iterator struct {
@ -31,36 +31,13 @@ func NewIteratorWithCap(n *Node, cap int) *Iterator {
}
func (iter *Iterator) ToHead() {
if iter.cur == nil {
iter.cur = iter.up
for iter.Prev() {
}
for iter.cur.parent != nil {
iter.cur = iter.cur.parent
}
for iter.cur.children[0] != nil {
iter.cur = iter.cur.children[0]
}
iter.SetNode(iter.cur)
iter.cur = nil
}
func (iter *Iterator) ToTail() {
if iter.cur == nil {
iter.cur = iter.up
for iter.Next() {
}
for iter.cur.parent != nil {
iter.cur = iter.cur.parent
}
for iter.cur.children[1] != nil {
iter.cur = iter.cur.children[1]
}
iter.SetNode(iter.cur)
iter.cur = nil
}
func (iter *Iterator) GetNode() *Node {
@ -73,10 +50,6 @@ func (iter *Iterator) SetNode(n *Node) {
iter.tstack.Clear()
}
func (iter *Iterator) Key() interface{} {
return iter.cur.key
}
func (iter *Iterator) Value() interface{} {
return iter.cur.value
}

View File

@ -1,35 +0,0 @@
package avlkeydup
import (
"sort"
"testing"
"github.com/474420502/focus/compare"
)
func TestIerator(t *testing.T) {
tree := New(compare.Int)
l := []int{5, 10, 100, 30, 40, 70, 45, 35, 23}
for _, v := range l {
tree.Put(v, v)
}
sort.Ints(l)
iter := tree.Iterator()
iter.ToHead()
for i := 0; iter.Next(); i++ {
if iter.Value() != l[i] {
t.Error(iter.Value(), l[i])
}
}
iter.ToTail()
iter.Prev()
for i := len(l) - 1; iter.Next(); i-- {
if iter.Value() != l[i] {
t.Error(iter.Value(), l[i])
}
}
}

View File

@ -4,27 +4,27 @@ import (
"github.com/474420502/focus/compare"
)
type Tree struct {
type Heap struct {
size int
elements []interface{}
Compare compare.Compare
}
func New(Compare compare.Compare) *Tree {
h := &Tree{Compare: Compare}
func New(Compare compare.Compare) *Heap {
h := &Heap{Compare: Compare}
h.elements = make([]interface{}, 16, 16)
return h
}
func (h *Tree) Size() int {
func (h *Heap) Size() int {
return h.size
}
func (h *Tree) Values() []interface{} {
func (h *Heap) Values() []interface{} {
return h.elements[0:h.size]
}
func (h *Tree) grow() {
func (h *Heap) grow() {
ecap := len(h.elements)
if h.size >= ecap {
ecap = ecap << 1
@ -34,27 +34,27 @@ func (h *Tree) grow() {
}
}
func (h *Tree) Empty() bool {
func (h *Heap) Empty() bool {
return h.size < 1
}
func (h *Tree) Clear() {
func (h *Heap) Clear() {
h.size = 0
}
func (h *Tree) Reborn() {
func (h *Heap) Reborn() {
h.size = 0
h.elements = make([]interface{}, 16, 16)
}
func (h *Tree) Top() (interface{}, bool) {
func (h *Heap) Top() (interface{}, bool) {
if h.size != 0 {
return h.elements[0], true
}
return nil, false
}
func (h *Tree) Put(v interface{}) {
func (h *Heap) Put(v interface{}) {
if v == nil {
return
}
@ -77,7 +77,7 @@ func (h *Tree) Put(v interface{}) {
h.elements[curidx] = v
}
func (h *Tree) slimming() {
func (h *Heap) slimming() {
elen := len(h.elements)
if elen >= 32 {
@ -92,7 +92,7 @@ func (h *Tree) slimming() {
}
func (h *Tree) Pop() (interface{}, bool) {
func (h *Heap) Pop() (interface{}, bool) {
if h.size == 0 {
return nil, false

View File

@ -1,21 +0,0 @@
rsync() {
FILE_NAME=$3 #iterator_test.go
SRC_DIR_NAME=$1 #vbtkey dir
DEST_DIR_NAME=$2 # vbtdupkey dir
cp ./$SRC_DIR_NAME/$FILE_NAME ./$DEST_DIR_NAME/$FILE_NAME
sed -i "s/package $SRC_DIR_NAME/package ${DEST_DIR_NAME}/" ./$DEST_DIR_NAME/$FILE_NAME
}
# 同步iterator_test
for dst in "vbtkeydup" "avlkey" "avlkeydup"
do
rsync "vbtkey" $dst "iterator_test.go"
done
# 同步iterator_test
for dst in "vbtdup" "avl" "avldup"
do
rsync "vbt" $dst "iterator_test.go"
done

View File

@ -1,6 +1,6 @@
package tree
// IBSTreeKey Compare函数可以自定义所以key不一定value, 可以是value结构体中一个属性
// IBSTreeKey Compare函数可以自定义所以key不一定value, 可以是value结构体中一个属性
type IBSTreeKey interface {
String() string
Size() int
@ -21,31 +21,7 @@ type IBSTree interface {
Clear()
// Values 返回先序遍历的值
Values() []interface{}
Get(value interface{}) (interface{}, bool)
Get(key interface{}) (interface{}, bool)
Put(value interface{})
Traversal(every func(v interface{}) bool, traversalMethod ...interface{})
}
type IBSTreeDup interface {
String() string
Size() int
Remove(key interface{}) (interface{}, bool)
Clear()
// Values 返回先序遍历的值
Values() []interface{}
Get(value interface{}) (interface{}, bool)
Put(value interface{}) bool
Traversal(every func(v interface{}) bool, traversalMethod ...interface{})
}
type IBSTreeDupKey interface {
String() string
Size() int
Remove(key interface{}) (interface{}, bool)
Clear()
// Values 返回先序遍历的值
Values() []interface{}
Get(key interface{}) (interface{}, bool)
Put(key, value interface{}) bool
Traversal(every func(k, v interface{}) bool, traversalMethod ...interface{})
}

View File

@ -1,197 +0,0 @@
package tried
import "github.com/davecgh/go-spew/spew"
// func (ts TriedString) WordIndex(idx uint) uint {
// w := ts[idx]
// if w >= 'a' && w <= 'z' {
// return uint(w) - 'a'
// } else if w >= 'A' && w <= 'Z' {
// return uint(w) - 'A' + 26
// } else {
// return uint(w) - '0' + 52
// }
// }
type Tried struct {
root *Node
wiStore *wordIndexStore
}
type Node struct {
data []*Node
value interface{}
}
// New 默认 WordIndexLower 意味着只支持小写
func New() *Tried {
tried := &Tried{}
tried.root = new(Node)
tried.wiStore = WordIndexDict[WordIndexLower]
return tried
}
// NewWithWordType 选择单词的类型 WordIndexLower 意味着只支持小写
func NewWithWordType(t WordIndexType) *Tried {
tried := &Tried{}
tried.root = new(Node)
tried.wiStore = WordIndexDict[t]
return tried
}
func (tried *Tried) Put(words string, values ...interface{}) {
cur := tried.root
var n *Node
bytes := []byte(words)
for i := 0; i < len(bytes); i++ {
w := tried.wiStore.Byte2Index(bytes[i])
if cur.data == nil {
cur.data = make([]*Node, tried.wiStore.DataSize)
}
if n = cur.data[w]; n == nil {
n = new(Node)
cur.data[w] = n
}
cur = n
}
if values != nil {
cur.value = values[0]
} else {
cur.value = tried
}
}
func (tried *Tried) Get(words string) interface{} {
cur := tried.root
var n *Node
bytes := []byte(words)
for i := 0; i < len(bytes); i++ {
w := tried.wiStore.Byte2Index(bytes[i]) //TODO: 升级Index 函数
if n = cur.data[w]; n == nil {
return nil
}
cur = n
}
return n.value
}
func (tried *Tried) Has(words string) bool {
return tried.Get(words) != nil
}
func (tried *Tried) HasPrefix(words string) bool {
cur := tried.root
var n *Node
bytes := []byte(words)
for i := 0; i < len(bytes); i++ {
w := tried.wiStore.Byte2Index(bytes[i]) //TODO: 升级Index 函数
if n = cur.data[w]; n == nil {
return false
}
cur = n
}
return true
}
func (tried *Tried) PrefixWords(words string) []string {
cur := tried.root
var n *Node
bytes := []byte(words)
var header []byte
for i := 0; i < len(bytes); i++ {
curbyte := bytes[i]
header = append(header, curbyte)
w := tried.wiStore.Byte2Index(curbyte)
if n = cur.data[w]; n == nil {
return nil
}
cur = n
}
var result []string
var traversal func([]byte, *Node)
traversal = func(prefix []byte, cur *Node) {
for i, n := range cur.data {
if n != nil {
nextPrefix := append(prefix, tried.wiStore.Index2Byte(uint(i)))
traversal(nextPrefix, n)
if n.value != nil {
result = append(result, string(append(header, nextPrefix...)))
}
}
}
}
// 拼接头
if n != nil {
if n.value != nil {
result = append(result, string(header))
}
traversal([]byte{}, n)
}
return result
}
func (tried *Tried) Traversal(every func(cidx uint, value interface{}) bool) {
var traversal func(*Node)
traversal = func(cur *Node) {
if cur != nil {
for i, n := range cur.data {
if n != nil {
if n.value != nil {
if !every(uint(i), n.value) {
return
}
}
traversal(n)
}
}
}
}
root := tried.root
traversal(root)
}
func (tried *Tried) WordsArray() []string {
var result []string
var traversal func([]byte, *Node)
traversal = func(prefix []byte, cur *Node) {
for i, n := range cur.data {
if n != nil {
nextPrefix := append(prefix, tried.wiStore.Index2Byte(uint(i)))
traversal(nextPrefix, n)
if n.value != nil {
result = append(result, string(nextPrefix))
}
}
}
}
if tried.root != nil {
traversal([]byte{}, tried.root)
}
return result
}
func (tried *Tried) String() string {
return spew.Sprint(tried.WordsArray())
}

View File

@ -1,152 +0,0 @@
package tried
var WordIndexDict map[WordIndexType]*wordIndexStore
func init() {
WordIndexDict = make(map[WordIndexType]*wordIndexStore)
WordIndexDict[WordIndexLower] = &wordIndexStore{WordIndexLower, wordIndexLower, indexWordLower, 26}
WordIndexDict[WordIndexUpper] = &wordIndexStore{WordIndexUpper, wordIndexUpper, indexWordUpper, 26}
WordIndexDict[WordIndexDigital] = &wordIndexStore{WordIndexDigital, wordIndexDigital, indexWordDigital, 10}
WordIndexDict[WordIndexUpperLower] = &wordIndexStore{WordIndexUpperLower, wordIndexUpperLower, indexWordUpperLower, 52}
WordIndexDict[WordIndexLowerDigital] = &wordIndexStore{WordIndexLowerDigital, wordIndexLowerDigital, indexWordLowerDigital, 36}
WordIndexDict[WordIndexUpperDigital] = &wordIndexStore{WordIndexUpperDigital, wordIndexUpperDigital, indexWordUpperDigital, 36}
WordIndexDict[WordIndexUpperLowerDigital] = &wordIndexStore{WordIndexUpperLowerDigital, wordIndexUpperLowerDigital, indexWordUpperLowerDigital, 62}
WordIndexDict[WordIndex256] = &wordIndexStore{WordIndex256, wordIndex256, indexWord256, 256}
WordIndexDict[WordIndex32to126] = &wordIndexStore{WordIndex32to126, wordIndex32to126, indexWord32to126, ('~' - ' ' + 1)}
}
// WordIndexType 单词统计的类型 eg. WordIndexLower 意味Put的单词只支持小写...
type WordIndexType int
const (
_ WordIndexType = iota
WordIndexLower
WordIndexUpper
WordIndexDigital
WordIndexUpperLower
WordIndexLowerDigital
WordIndexUpperDigital
WordIndexUpperLowerDigital
WordIndex256
WordIndex32to126
)
type wordIndexStore struct {
Type WordIndexType
Byte2Index func(byte) uint
Index2Byte func(uint) byte
DataSize uint
}
func wordIndexLower(w byte) uint {
return uint(w) - 'a'
}
func indexWordLower(w uint) byte {
return byte(w) + 'a'
}
//
func wordIndexUpper(w byte) uint {
return uint(w) - 'A'
}
func indexWordUpper(w uint) byte {
return byte(w) + 'A'
}
//
func wordIndexDigital(w byte) uint {
return uint(w) - '0'
}
func indexWordDigital(w uint) byte {
return byte(w) + '0'
}
//
func wordIndexUpperLower(w byte) uint {
iw := uint(w)
if iw >= 'a' {
return iw - 'a'
}
return iw - 'A' + 26
}
func indexWordUpperLower(w uint) byte {
if w >= 26 {
return byte(w) - 26 + 'A'
}
return byte(w) + 'a'
}
//
func wordIndexLowerDigital(w byte) uint {
iw := uint(w)
if iw >= 'a' {
return iw - 'a'
}
return iw - '0' + 26
}
func indexWordLowerDigital(w uint) byte {
if w >= 26 {
return byte(w) - 26 + '0'
}
return byte(w) + 'a'
}
//
func wordIndexUpperDigital(w byte) uint {
iw := uint(w)
if iw >= 'A' {
return iw - 'A'
}
return iw - '0' + 26
}
func indexWordUpperDigital(w uint) byte {
if w >= 26 {
return byte(w) - 26 + '0'
}
return byte(w) + 'A'
}
//
func wordIndexUpperLowerDigital(w byte) uint {
iw := uint(w)
if iw >= 'a' {
return iw - 'a'
} else if iw >= 'A' {
return iw - 'A' + 26
}
return iw - '0' + 52
}
func indexWordUpperLowerDigital(w uint) byte {
if w >= 52 {
return byte(w) - 52 + '0'
} else if w >= 26 {
return byte(w) - 26 + 'A'
}
return byte(w) + 'a'
}
// wordIndex256 all byte 支持中文
func wordIndex256(w byte) uint {
return uint(w)
}
func indexWord256(w uint) byte {
return byte(w)
}
// wordIndex32to126 空格-~ 0-9 a-z A-Z 符号等
func wordIndex32to126(w byte) uint {
return uint(w) - ' '
}
func indexWord32to126(w uint) byte {
return byte(w) + ' '
}

View File

@ -1,384 +0,0 @@
package tried
import (
"bytes"
"encoding/gob"
"os"
"sort"
"testing"
"github.com/davecgh/go-spew/spew"
"github.com/Pallinder/go-randomdata"
)
func CompareSliceWithSorted(source, words []string) (bool, string) {
sort.Slice(words, func(i, j int) bool {
if words[i] < words[j] {
return true
}
return false
})
// source := tried.WordsArray()
sort.Slice(source, func(i, j int) bool {
if source[i] < source[j] {
return true
}
return false
})
result1 := spew.Sprint(source)
result2 := spew.Sprint(words)
if result1 != result2 {
return false, spew.Sprint(result1, " != ", result2)
}
return true, ""
}
func TestTried_Has(t *testing.T) {
var tried *Tried
tried = NewWithWordType(WordIndexLower)
tried.Put("ads")
tried.Put("zadads")
tried.Put("asdgdf")
if !tried.Has("ads") {
t.Error("ads is exist, but not has")
}
if !tried.HasPrefix("ad") {
t.Error("ads is exist, but not HasPrefix")
}
if !tried.HasPrefix("za") {
t.Error("ads is exist, but not HasPrefix")
}
if tried.HasPrefix("fsdf") {
t.Error("fsdf is not exist, but HasPrefix")
}
if len(tried.String()) < 10 {
t.Error(tried.WordsArray())
}
}
func TestTried_PrefixWords(t *testing.T) {
var tried *Tried
var wordsCollection []string
var input []string
var wordsList [][]string
var inputParams [][]string
var triedList []*Tried
triedList = append(triedList, NewWithWordType(WordIndexLower))
inputParams = append(inputParams, []string{"ad", "adf"})
wordsList = append(wordsList, []string{"ad", "adfsxzcdas", "adfadsasd"})
triedList = append(triedList, NewWithWordType(WordIndexUpper))
inputParams = append(inputParams, []string{"AD", "ADF"})
wordsList = append(wordsList, []string{"AD", "ADFSXZCDAS", "ADFADSASD"})
triedList = append(triedList, NewWithWordType(WordIndexUpperLower))
inputParams = append(inputParams, []string{"aD", "aDf"})
wordsList = append(wordsList, []string{"aDF", "aDfsxzcdas", "aDfadsasd"})
triedList = append(triedList, NewWithWordType(WordIndexUpperDigital))
inputParams = append(inputParams, []string{"A09D", "A09DF"})
wordsList = append(wordsList, []string{"A09D", "A09DFSXZCD312AS", "A09DFA32DSASD"})
triedList = append(triedList, NewWithWordType(WordIndexLowerDigital))
inputParams = append(inputParams, []string{"a09d", "a09df"})
wordsList = append(wordsList, []string{"a09d", "a09dfsxzcd312as", "a09dfa32dsasd"})
triedList = append(triedList, NewWithWordType(WordIndexUpperLowerDigital))
inputParams = append(inputParams, []string{"A09d", "A09dZ"})
wordsList = append(wordsList, []string{"A09d", "A09dZsxzcd312as", "A09dZa32dsasd"})
triedList = append(triedList, NewWithWordType(WordIndex256))
inputParams = append(inputParams, []string{"阿萨德", "阿萨德!"})
wordsList = append(wordsList, []string{"阿萨德", "阿萨德!@$*#))(#*", "阿萨德!╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳▁▂▃▄▅▆▇█ ▉ ▊▋▌▍▎▏"})
triedList = append(triedList, NewWithWordType(WordIndex32to126))
inputParams = append(inputParams, []string{" `", " `<"})
wordsList = append(wordsList, []string{" `21`3tcdbxcfhyop8901zc[]\\'/?()#$%^&**! ", " `<AZaz09~ dys!@#$)(*^$#", " `<>.,?/"})
for i := 0; i < len(triedList); i++ {
tried = triedList[i]
input = inputParams[i]
wordsCollection = wordsList[i]
for _, words := range wordsCollection {
tried.Put(words)
}
var prefixWords []string
prefixWords = tried.PrefixWords(input[0])
if ok, errorResult := CompareSliceWithSorted(prefixWords, wordsCollection); !ok {
t.Error(errorResult)
}
prefixWords = tried.PrefixWords(input[1])
if ok, _ := CompareSliceWithSorted(prefixWords, wordsCollection); ok {
t.Error("should be not ok")
}
if len(prefixWords) != 2 {
t.Error(prefixWords, " Size of Array should be 2")
}
if ok, errorResult := CompareSliceWithSorted(prefixWords, wordsCollection[1:]); !ok {
t.Error(errorResult)
}
// t.Error(tried.WordsArray())
}
}
func TestTried_NewWith(t *testing.T) {
var tried *Tried
var wordsCollection []string
var wordsList [][]string
var triedList []*Tried
triedList = append(triedList, NewWithWordType(WordIndexLower))
wordsList = append(wordsList, []string{"adazx", "assdfhgnvb", "ewqyiouyasdfmzvxz"})
triedList = append(triedList, NewWithWordType(WordIndexUpper))
wordsList = append(wordsList, []string{"ADFSZ", "DEFASEWRQWER", "GFHJERQWREWTNBVFGFH"})
triedList = append(triedList, NewWithWordType(WordIndexUpperLower))
wordsList = append(wordsList, []string{"adazxAZDSAFASZRETHGFTUIPK", "assdfhgDSFGnvb", "yaXZLMPOIQsdGHFfmFBzvxz"})
triedList = append(triedList, NewWithWordType(WordIndexUpperDigital))
wordsList = append(wordsList, []string{"AZ3428934470193", "ZPQPDEK09876543629812", "AZEWIRU0192456FDEWR9032"})
triedList = append(triedList, NewWithWordType(WordIndexLowerDigital))
wordsList = append(wordsList, []string{"az3428934470193", "zpqwe0987654362sf9812", "az21301az09azdstr540"})
triedList = append(triedList, NewWithWordType(WordIndexUpperLowerDigital))
wordsList = append(wordsList, []string{"azAZ09", "aRGFDSFDSzAasdZ06789", "A28374JHFudfsu09qwzzdsw874FDSAZfer"})
triedList = append(triedList, NewWithWordType(WordIndex256))
wordsList = append(wordsList, []string{"21`3tcdbxcfhyop8901zc[]\\'/?()#$%^&**! 09-阿萨德发生的官方说的对符合规定", "符号!@$*#))(#*", "╜╝╞╟╠╡╢╣╤╥╦╧╨╩╪╫╬╭╮╯╰╱╲╳▁▂▃▄▅▆▇█ ▉ ▊▋▌▍▎▏"})
triedList = append(triedList, NewWithWordType(WordIndex32to126))
wordsList = append(wordsList, []string{" 21`3tcdbxcfhyop8901zc[]\\'/?()#$%^&**! ", "AZaz09~ dys!@#$)(*^$#", "<>.,?/"})
for i := 0; i < len(triedList); i++ {
tried = triedList[i]
wordsCollection = wordsList[i]
for _, words := range wordsCollection {
tried.Put(words)
if tried.Get(words) == nil {
t.Error("should be not nil the type is ", tried.wiStore.Type)
}
}
// t.Error(tried.WordsArray())
}
}
func TestTried_String(t *testing.T) {
var tried *Tried
var wordsCollection []string
var wordsList [][]string
var triedList []*Tried
triedList = append(triedList, NewWithWordType(WordIndexLower))
wordsList = append(wordsList, []string{"adazx", "assdfhgnvb", "ewqyiouyasdfmzvxz"})
triedList = append(triedList, NewWithWordType(WordIndexUpper))
wordsList = append(wordsList, []string{"ADFSZ", "DEFASEWRQWER", "GFHJERQWREWTNBVFGFH"})
triedList = append(triedList, NewWithWordType(WordIndexDigital))
wordsList = append(wordsList, []string{"093875239457", "09123406534", "0912340846"})
triedList = append(triedList, NewWithWordType(WordIndexUpperLower))
wordsList = append(wordsList, []string{"adazxAZDSAFASZRETHGFTUIPK", "assdfhgDSFGnvb", "yaXZLMPOIQsdGHFfmFBzvxz"})
triedList = append(triedList, NewWithWordType(WordIndexUpperDigital))
wordsList = append(wordsList, []string{"AZ3428934470193", "ZPQPDEK09876543629812", "AZEWIRU0192456FDEWR9032"})
triedList = append(triedList, NewWithWordType(WordIndexLowerDigital))
wordsList = append(wordsList, []string{"az3428934470193", "zpqwe0987654362sf9812", "az21301az09azdstr540"})
triedList = append(triedList, NewWithWordType(WordIndexUpperLowerDigital))
wordsList = append(wordsList, []string{"azAZ09", "aRGFDSFDSzAasdZ06789", "A28374JHFudfsu09qwzzdsw874FDSAZfer"})
triedList = append(triedList, NewWithWordType(WordIndex256))
wordsList = append(wordsList, []string{"21`3tcdbxcf囉hyop打算8901zc[]\\'/?()#$%^&**!\x01 09-213", "的支持中文", "!@$*#)中文)(#*", `\/213dsfsdf`})
triedList = append(triedList, NewWithWordType(WordIndex32to126))
wordsList = append(wordsList, []string{" 21`3tcdbxcfhyop8901zc[]\\'/?()#$%^&**! ", "AZaz09~ dys!@#$)(*^$#", "<>.,?/"})
for i := 0; i < len(triedList); i++ {
tried = triedList[i]
wordsCollection = wordsList[i]
for _, words := range wordsCollection {
tried.Put(words)
if tried.Get(words) == nil {
t.Error("should be not nil the type is ", tried.wiStore.Type)
}
}
resultArray := tried.WordsArray()
if ok, errorResult := CompareSliceWithSorted(resultArray, wordsCollection); !ok {
t.Error(errorResult)
}
// t.Error(tried.WordsArray())
}
}
func TestTried_PutAndGet1(t *testing.T) {
tried := New()
tried.Put(("asdf"))
tried.Put(("hehe"), "hehe")
tried.Put(("xixi"), 3)
var result interface{}
result = tried.Get("asdf")
if result != tried {
t.Error("result should be 3")
}
result = tried.Get("xixi")
if result != 3 {
t.Error("result should be 3")
}
result = tried.Get("hehe")
if result != "hehe" {
t.Error("result should be hehe")
}
result = tried.Get("haha")
if result != nil {
t.Error("result should be nil")
}
result = tried.Get("b")
if result != nil {
t.Error("result should be nil")
}
}
func TestTried_Traversal(t *testing.T) {
tried := New()
tried.Put("asdf")
tried.Put(("abdf"), "ab")
tried.Put(("hehe"), "hehe")
tried.Put(("xixi"), 3)
var result []interface{}
tried.Traversal(func(idx uint, v interface{}) bool {
// t.Error(idx, v)
result = append(result, v)
return true
})
if result[0] != "ab" {
t.Error(result[0])
}
if result[1] != tried {
t.Error(result[1])
}
if result[2] != "hehe" {
t.Error(result[2])
}
if result[3] != 3 {
t.Error(result[3])
}
}
func TesStoreData(t *testing.T) {
var l []string
const N = 1000000
for i := 0; i < N; i++ {
var content []rune
for c := 0; c < randomdata.Number(5, 15); c++ {
char := randomdata.Number(0, 26) + 'a'
content = append(content, rune(byte(char)))
}
l = append(l, (string(content)))
}
var result bytes.Buffer
encoder := gob.NewEncoder(&result)
encoder.Encode(l)
lbytes := result.Bytes()
f, _ := os.OpenFile("tried.log", os.O_CREATE|os.O_TRUNC|os.O_WRONLY, 0666)
f.Write(lbytes)
}
func Load() []string {
var result []string
f, err := os.Open("tried.log")
if err != nil {
panic("先执行TesStoreData 然后再测试Benchmark")
}
gob.NewDecoder(f).Decode(&result)
return result
}
func BenchmarkTried_Put(b *testing.B) {
var data []string
b.N = 1000000
count := 10
// for i := 0; i < b.N; i++ {
// var content []rune
// for c := 0; c < randomdata.Number(5, 15); c++ {
// char := randomdata.Number(0, 26) + 'a'
// content = append(content, rune(byte(char)))
// }
// data = append(data, (string(content)))
// }
data = Load()
b.ResetTimer()
b.N = b.N * count
for c := 0; c < count; c++ {
tried := New()
for _, v := range data {
tried.Put(v)
}
}
}
func BenchmarkTried_Get(b *testing.B) {
b.StopTimer()
var data []string
b.N = 1000000
count := 10
// for i := 0; i < b.N; i++ {
// var content []rune
// for c := 0; c < randomdata.Number(5, 15); c++ {
// char := randomdata.Number(0, 26) + 'a'
// content = append(content, rune(byte(char)))
// }
// data = append(data, string(content))
// }
data = Load()
b.N = b.N * count
tried := New()
for _, v := range data {
tried.Put(v)
}
b.StartTimer()
for c := 0; c < count; c++ {
for _, v := range data {
tried.Get(v)
}
}
}

View File

@ -1,7 +1,7 @@
package vbt
import (
lastack "github.com/474420502/focus/stack/listarraystack"
"github.com/474420502/focus/stack/listarraystack"
)
type Iterator struct {
@ -31,36 +31,13 @@ func NewIteratorWithCap(n *Node, cap int) *Iterator {
}
func (iter *Iterator) ToHead() {
if iter.cur == nil {
iter.cur = iter.up
for iter.Prev() {
}
for iter.cur.parent != nil {
iter.cur = iter.cur.parent
}
for iter.cur.children[0] != nil {
iter.cur = iter.cur.children[0]
}
iter.SetNode(iter.cur)
iter.cur = nil
}
func (iter *Iterator) ToTail() {
if iter.cur == nil {
iter.cur = iter.up
for iter.Next() {
}
for iter.cur.parent != nil {
iter.cur = iter.cur.parent
}
for iter.cur.children[1] != nil {
iter.cur = iter.cur.children[1]
}
iter.SetNode(iter.cur)
iter.cur = nil
}
func (iter *Iterator) GetNode() *Node {
@ -135,7 +112,6 @@ func (iter *Iterator) Next() (result bool) {
return false
}
func (iter *Iterator) GetPrev(cur *Node, idx int) *Node {
// iter := NewIterator(cur)

View File

@ -1,35 +0,0 @@
package vbt
import (
"sort"
"testing"
"github.com/474420502/focus/compare"
)
func TestIerator(t *testing.T) {
tree := New(compare.Int)
l := []int{5, 10, 100, 30, 40, 70, 45, 35, 23}
for _, v := range l {
tree.Put(v)
}
sort.Ints(l)
iter := tree.Iterator()
iter.ToHead()
for i := 0; iter.Next(); i++ {
if iter.Value() != l[i] {
t.Error(iter.Value(), l[i])
}
}
iter.ToTail()
iter.Prev()
for i := len(l) - 1; iter.Next(); i-- {
if iter.Value() != l[i] {
t.Error(iter.Value(), l[i])
}
}
}

View File

@ -61,7 +61,7 @@ func (tree *Tree) Size() int {
return tree.root.size
}
func (tree *Tree) IndexNode(idx int) *Node {
func (tree *Tree) indexNode(idx int) *Node {
cur := tree.root
if idx >= 0 {
for cur != nil {
@ -93,7 +93,7 @@ func (tree *Tree) IndexNode(idx int) *Node {
}
func (tree *Tree) Index(idx int) (interface{}, bool) {
n := tree.IndexNode(idx)
n := tree.indexNode(idx)
if n != nil {
return n.value, true
}
@ -117,7 +117,7 @@ func (tree *Tree) IndexRange(idx1, idx2 int) (result []interface{}, ok bool) { /
ok = false
}
n := tree.IndexNode(idx1)
n := tree.indexNode(idx1)
tree.iter.SetNode(n)
iter := tree.iter
result = make([]interface{}, 0, idx1-idx2)
@ -139,7 +139,7 @@ func (tree *Tree) IndexRange(idx1, idx2 int) (result []interface{}, ok bool) { /
ok = false
}
if n := tree.IndexNode(idx1); n != nil {
if n := tree.indexNode(idx1); n != nil {
tree.iter.SetNode(n)
iter := tree.iter
result = make([]interface{}, 0, idx2-idx1)
@ -161,15 +161,15 @@ func (tree *Tree) IndexRange(idx1, idx2 int) (result []interface{}, ok bool) { /
}
func (tree *Tree) RemoveIndex(idx int) (interface{}, bool) {
n := tree.IndexNode(idx)
n := tree.indexNode(idx)
if n != nil {
tree.RemoveNode(n)
tree.removeNode(n)
return n.value, true
}
return nil, false
}
func (tree *Tree) RemoveNode(n *Node) {
func (tree *Tree) removeNode(n *Node) {
if tree.root.size == 1 {
tree.root = nil
// return n
@ -230,7 +230,7 @@ func (tree *Tree) RemoveNode(n *Node) {
func (tree *Tree) Remove(key interface{}) (interface{}, bool) {
if n, ok := tree.GetNode(key); ok {
tree.RemoveNode(n)
tree.removeNode(n)
return n.value, true
}
// return nil

View File

@ -1,248 +0,0 @@
package vbtdup
import (
lastack "github.com/474420502/focus/stack/listarraystack"
)
type Iterator struct {
dir int
up *Node
cur *Node
tstack *lastack.Stack
// curnext *Node
}
func initIterator(avltree *Tree) *Iterator {
iter := &Iterator{tstack: lastack.New()}
iter.up = avltree.root
return iter
}
func NewIterator(n *Node) *Iterator {
iter := &Iterator{tstack: lastack.New()}
iter.up = n
return iter
}
func NewIteratorWithCap(n *Node, cap int) *Iterator {
iter := &Iterator{tstack: lastack.NewWithCap(cap)}
iter.up = n
return iter
}
func (iter *Iterator) GetNode() *Node {
return iter.cur
}
func (iter *Iterator) ToHead() {
if iter.cur == nil {
iter.cur = iter.up
}
for iter.cur.parent != nil {
iter.cur = iter.cur.parent
}
for iter.cur.children[0] != nil {
iter.cur = iter.cur.children[0]
}
iter.SetNode(iter.cur)
iter.cur = nil
}
func (iter *Iterator) ToTail() {
if iter.cur == nil {
iter.cur = iter.up
}
for iter.cur.parent != nil {
iter.cur = iter.cur.parent
}
for iter.cur.children[1] != nil {
iter.cur = iter.cur.children[1]
}
iter.SetNode(iter.cur)
iter.cur = nil
}
func (iter *Iterator) SetNode(n *Node) {
iter.up = n
iter.dir = 0
iter.tstack.Clear()
}
func (iter *Iterator) Value() interface{} {
return iter.cur.value
}
func (iter *Iterator) GetNext(cur *Node, idx int) *Node {
// iter := NewIterator(cur)
iter.SetNode(cur)
iter.curPushNextStack(iter.up)
iter.up = iter.getNextUp(iter.up)
for i := 0; i < idx; i++ {
if iter.tstack.Size() == 0 {
if iter.up == nil {
return nil
}
iter.tstack.Push(iter.up)
iter.up = iter.getNextUp(iter.up)
}
if v, ok := iter.tstack.Pop(); ok {
iter.cur = v.(*Node)
if i == idx-1 {
return iter.cur
}
iter.curPushNextStack(iter.cur)
} else {
return nil
}
}
return cur
}
func (iter *Iterator) Next() (result bool) {
if iter.dir > -1 {
if iter.dir == 1 && iter.cur != nil {
iter.tstack.Clear()
iter.curPushNextStack(iter.cur)
iter.up = iter.getNextUp(iter.cur)
}
iter.dir = -1
}
if iter.tstack.Size() == 0 {
if iter.up == nil {
return false
}
iter.tstack.Push(iter.up)
iter.up = iter.getNextUp(iter.up)
}
if v, ok := iter.tstack.Pop(); ok {
iter.cur = v.(*Node)
iter.curPushNextStack(iter.cur)
return true
}
return false
}
func (iter *Iterator) GetPrev(cur *Node, idx int) *Node {
// iter := NewIterator(cur)
iter.SetNode(cur)
iter.curPushPrevStack(iter.up)
iter.up = iter.getPrevUp(iter.up)
for i := 0; i < idx; i++ {
if iter.tstack.Size() == 0 {
if iter.up == nil {
return nil
}
iter.tstack.Push(iter.up)
iter.up = iter.getPrevUp(iter.up)
}
if v, ok := iter.tstack.Pop(); ok {
iter.cur = v.(*Node)
if i == idx-1 {
return iter.cur
}
iter.curPushPrevStack(iter.cur)
} else {
return nil
}
}
return cur
}
func (iter *Iterator) Prev() (result bool) {
if iter.dir < 1 { // 非 1(next 方向定义 -1 为 prev)
if iter.dir == -1 && iter.cur != nil { // 如果上次为prev方向, 则清空辅助计算的栈
iter.tstack.Clear()
iter.curPushPrevStack(iter.cur) // 把当前cur计算的回朔
iter.up = iter.getPrevUp(iter.cur) // cur 寻找下个要计算up
}
iter.dir = 1
}
// 如果栈空了, 把up的递归计算入栈, 重新计算 下次的up值
if iter.tstack.Size() == 0 {
if iter.up == nil {
return false
}
iter.tstack.Push(iter.up)
iter.up = iter.getPrevUp(iter.up)
}
if v, ok := iter.tstack.Pop(); ok {
iter.cur = v.(*Node)
iter.curPushPrevStack(iter.cur)
return true
}
// 如果再次计算的栈为空, 则只能返回false
return false
}
func getRelationship(cur *Node) int {
if cur.parent.children[1] == cur {
return 1
}
return 0
}
func (iter *Iterator) getPrevUp(cur *Node) *Node {
for cur.parent != nil {
if getRelationship(cur) == 1 { // next 在 降序 小值. 如果child在右边, parent 比 child 小, parent才有效, 符合降序
return cur.parent
}
cur = cur.parent
}
return nil
}
func (iter *Iterator) curPushPrevStack(cur *Node) {
Prev := cur.children[0] // 当前的左然后向右找, 找到最大, 就是最接近cur 并且小于cur的值
if Prev != nil {
iter.tstack.Push(Prev)
for Prev.children[1] != nil {
Prev = Prev.children[1]
iter.tstack.Push(Prev) // 入栈 用于回溯
}
}
}
func (iter *Iterator) getNextUp(cur *Node) *Node {
for cur.parent != nil {
if getRelationship(cur) == 0 { // Prev 在 降序 大值. 如果child在左边, parent 比 child 大, parent才有效 , 符合降序
return cur.parent
}
cur = cur.parent
}
return nil
}
func (iter *Iterator) curPushNextStack(cur *Node) {
next := cur.children[1]
if next != nil {
iter.tstack.Push(next)
for next.children[0] != nil {
next = next.children[0]
iter.tstack.Push(next)
}
}
}

View File

@ -1,35 +0,0 @@
package vbtdup
import (
"sort"
"testing"
"github.com/474420502/focus/compare"
)
func TestIerator(t *testing.T) {
tree := New(compare.Int)
l := []int{5, 10, 100, 30, 40, 70, 45, 35, 23}
for _, v := range l {
tree.Put(v)
}
sort.Ints(l)
iter := tree.Iterator()
iter.ToHead()
for i := 0; iter.Next(); i++ {
if iter.Value() != l[i] {
t.Error(iter.Value(), l[i])
}
}
iter.ToTail()
iter.Prev()
for i := len(l) - 1; iter.Next(); i-- {
if iter.Value() != l[i] {
t.Error(iter.Value(), l[i])
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,844 +0,0 @@
package vbtdup
import (
"bytes"
"encoding/gob"
"io/ioutil"
"log"
"sort"
"testing"
"github.com/Pallinder/go-randomdata"
"github.com/davecgh/go-spew/spew"
"github.com/474420502/focus/compare"
)
func loadTestData() []int {
data, err := ioutil.ReadFile("../l.log")
if err != nil {
log.Println(err)
}
var l []int
decoder := gob.NewDecoder(bytes.NewReader(data))
decoder.Decode(&l)
return l
}
func TestIteratorHeadTail(t *testing.T) {
tree := New(compare.Int)
l := []int{1, 7, 14, 14, 16, 17, 20, 30, 21, 40, 50, 3, 40, 40, 40, 15, 100}
for _, v := range l {
tree.Put(v)
}
iter := tree.Iterator()
iter.ToHead() // 从小到大
iter.Next()
if iter.Value() != 1 {
t.Error("value error", iter.Value())
}
iter.ToTail()
iter.Prev()
if iter.Value() != 100 {
t.Error("value error", iter.Value())
}
for n := 0; n < 500; n++ {
tree := New(compare.Int)
var results []int
for i := 0; i < 50; i++ {
v := randomdata.Number(0, 5000)
if ok := tree.Put(v); ok {
results = append(results, v)
}
}
result := tree.GetAround(5001)
iter = tree.Iterator()
iter.ToTail()
iter.Prev()
if iter.Value() != result[0] {
t.Error("ToTail error", result, iter.Value())
}
result = tree.GetAround(-1)
iter.ToHead()
iter.Next()
if iter.Value() != result[2] {
t.Error("ToTail error", result, iter.Value())
}
}
}
func TestLargePushRemove(t *testing.T) {
for n := 0; n < 10; n++ {
tree := New(compare.Int)
var results []int
for i := 0; i < 50000; i++ {
v := randomdata.Number(0, 100000000)
if ok := tree.Put(v); ok {
results = append(results, v)
}
}
if tree.Size() != len(results) {
t.Error("Szie error", tree.Size(), len(results))
}
for i := 0; i < len(results)-10; i++ {
tree.Remove(results[i])
}
results = results[len(results)-10:]
if tree.Size() != 10 {
t.Error("Szie error")
}
sort.Slice(results, func(i, j int) bool {
if results[i] < results[j] {
return true
}
return false
})
if spew.Sprint(results) != spew.Sprint(tree.Values()) {
t.Error("tree is error")
}
for i := 0; i < 10; i++ {
v1 := results[i]
v2, ok := tree.Index(i)
if !ok {
t.Error("not ok")
}
if v1 != v2 {
t.Error("v1(", v1, ") != v2(", v2, ")??")
}
}
tree.Clear()
if tree.String() != "VBTree-Dup\nnil" {
t.Error("tree String is error")
}
}
}
func TestRemoveIndex(t *testing.T) {
tree := New(compare.Int)
l := []int{7, 14, 14, 14, 16, 1, 40, 15}
for _, v := range l {
tree.Put(v)
}
// [1 7 14 14 14 15 16 40]
var result string
result = spew.Sprint(tree.Values())
if result != "[1 7 14 15 16 40]" {
t.Error("result = ", result, " should be [1 7 14 15 16 40]")
}
tree.RemoveIndex(3)
result = spew.Sprint(tree.Values())
if result != "[1 7 14 16 40]" {
t.Error("result is error")
}
tree.RemoveIndex(-1)
result = spew.Sprint(tree.Values())
if result != "[1 7 14 16]" {
t.Error("result is error")
}
tree.RemoveIndex(0)
result = spew.Sprint(tree.Values())
if result != "[7 14 16]" {
t.Error("result is error")
}
if tree.Size() != 3 {
t.Error("size is error")
}
for tree.Size() != 0 {
tree.RemoveIndex(0)
}
if tree.root != nil {
t.Error("tree roor is not error")
}
}
func TestIndexRange(t *testing.T) {
tree := New(compare.Int)
l := []int{7, 14, 14, 14, 16, 17, 20, 30, 21, 40, 50, 3, 40, 40, 40, 15}
for _, v := range l {
tree.Put(v)
}
// [3 7 14 15 16 17 20 21 30 40 50]
// t.Error(tree.Values(), tree.Size())
// t.Error(tree.debugString())
var result string
result = spew.Sprint(tree.IndexRange(0, 5))
if result != "[3 7 14 15 16 17] true" {
t.Error(result)
}
result = spew.Sprint(tree.IndexRange(2, 5))
if result != "[14 15 16 17] true" {
t.Error(result)
}
result = spew.Sprint(tree.IndexRange(5, 100))
if result != "[17 20 21 30 40 50] false" {
t.Error(result)
}
result = spew.Sprint(tree.IndexRange(10, 0)) // size = 11, index max = 10
if result != "[50 40 30 21 20 17 16 15 14 7 3] true" {
t.Error(result)
}
result = spew.Sprint(tree.IndexRange(11, 0)) // size = 11, index max = 10
if result != "[50 40 30 21 20 17 16 15 14 7 3] false" {
t.Error(result)
}
result = spew.Sprint(tree.IndexRange(4, 1)) // size = 11, index max = 10
if result != "[16 15 14 7] true" {
t.Error(result)
}
result = spew.Sprint(tree.IndexRange(-1, -5)) // size = 11, index max = 10
if result != "[50 40 30 21 20] true" {
t.Error(result)
}
result = spew.Sprint(tree.IndexRange(-1, -11)) // size = 11, index max = 0 - 10 (-1,-11)
if result != "[50 40 30 21 20 17 16 15 14 7 3] true" {
t.Error(result)
}
result = spew.Sprint(tree.IndexRange(-1, -12)) // size = 11, index max = 0 - 10 (-1,-11)
if result != "[50 40 30 21 20 17 16 15 14 7 3] false" {
t.Error(result)
}
result = spew.Sprint(tree.IndexRange(-5, -1)) // size = 11, index max = 0 - 10 (-1,-11)
if result != "[20 21 30 40 50] true" {
t.Error(result)
}
// [3 7 14 15 16 17 20 21 30 40 50]
result = spew.Sprint(tree.IndexRange(-5, 5)) //
if result != "[20 17] true" {
t.Error(result)
}
result = spew.Sprint(tree.IndexRange(5, -5)) //
if result != "[17 20] true" {
t.Error(result)
}
result = spew.Sprint(tree.IndexRange(-1, 6)) //
if result != "[50 40 30 21 20] true" {
t.Error(result)
}
}
func TestGetAround(t *testing.T) {
tree := New(compare.Int)
for _, v := range []int{7, 14, 14, 14, 16, 17, 20, 30, 21, 40, 50, 3, 40, 40, 40, 15} {
tree.Put(v)
}
var Result string
Result = spew.Sprint(tree.GetAround(17))
if Result != "[16 17 20]" {
t.Error(tree.Values())
t.Error("17 is root, tree.GetAround(17)) is error", Result)
t.Error(tree.debugString())
}
Result = spew.Sprint(tree.GetAround(3))
if Result != "[<nil> 3 7]" {
t.Error(tree.Values())
t.Error("tree.GetAround(3)) is error", Result)
t.Error(tree.debugString())
}
Result = spew.Sprint(tree.GetAround(40))
if Result != "[30 40 50]" {
t.Error(tree.Values())
t.Error("tree.GetAround(40)) is error", Result)
t.Error(tree.debugString())
}
Result = spew.Sprint(tree.GetAround(50))
if Result != "[40 50 <nil>]" {
t.Error(tree.Values())
t.Error("tree.GetAround(50)) is error", Result)
t.Error(tree.debugString())
}
Result = spew.Sprint(tree.GetAround(18))
if Result != "[17 <nil> 20]" {
t.Error(tree.Values())
t.Error("18 is not in list, tree.GetAround(18)) is error", Result)
t.Error(tree.debugString())
}
Result = spew.Sprint(tree.GetAround(5))
if Result != "[3 <nil> 7]" {
t.Error(tree.Values())
t.Error("5 is not in list, tree.GetAround(5)) is error", Result)
t.Error(tree.debugString())
}
Result = spew.Sprint(tree.GetAround(2))
if Result != "[<nil> <nil> 3]" {
t.Error(tree.Values())
t.Error("2 is not in list, tree.GetAround(2)) is error", Result)
t.Error(tree.debugString())
}
Result = spew.Sprint(tree.GetAround(100))
if Result != "[50 <nil> <nil>]" {
t.Error(tree.Values())
t.Error("50 is not in list, tree.GetAround(50)) is error", Result)
t.Error(tree.debugString())
}
}
// // for test error case
// func TestPutComparatorRandom(t *testing.T) {
// for n := 0; n < 300000; n++ {
// tree := New(compare.Int)
// godsavl := avltree.NewWithIntComparator()
// content := ""
// m := make(map[int]int)
// for i := 0; len(m) < 10; i++ {
// v := randomdata.Number(0, 65535)
// if _, ok := m[v]; !ok {
// m[v] = v
// content += spew.Sprint(v) + ","
// tree.Put(v, v)
// godsavl.Put(v, v)
// }
// }
// s1 := spew.Sprint(tree.Values())
// s2 := spew.Sprint(godsavl.Values())
// if s1 != s2 {
// t.Error(godsavl.String())
// t.Error(tree.debugString())
// t.Error(content, n)
// break
// }
// }
// }
func TestGet(t *testing.T) {
tree := New(compare.Int)
for _, v := range []int{2383, 7666, 3055, 39016, 57092, 27897, 36513, 1562, 22574, 23202} {
tree.Put(v)
}
for _, v := range []int{2383, 7666, 3055, 39016, 57092, 27897, 36513, 1562, 22574, 23202} {
v, ok := tree.Get(v)
if !ok {
t.Error("the val not found ", v)
}
}
if v, ok := tree.Get(10000); ok {
t.Error("the val(1000) is not in tree, but is found", v)
}
}
func TestDupGetRange(t *testing.T) {
tree := New(compare.Int)
for _, v := range []int{5, 10, 13, 5, 17, 1, 2, 10, 40, 30, 1} {
tree.Put(v)
}
result := tree.GetRange(0, 20)
if spew.Sprint(result) != "[1 2 5 10 13 17]" {
t.Error(result)
}
result = tree.GetRange(0, 8)
if spew.Sprint(result) != "[1 2 5]" {
t.Error(result)
}
result = tree.GetRange(-5, -1)
if spew.Sprint(result) != "[]" {
t.Error(result)
}
result = tree.GetRange(7, 20)
if spew.Sprint(result) != "[10 13 17]" {
t.Error(result)
}
result = tree.GetRange(30, 40)
if spew.Sprint(result) != "[30 40]" {
t.Error(result)
}
result = tree.GetRange(30, 60)
if spew.Sprint(result) != "[30 40]" {
t.Error(result)
}
result = tree.GetRange(40, 40)
if spew.Sprint(result) != "[40]" {
t.Error(result)
}
result = tree.GetRange(50, 60)
if spew.Sprint(result) != "[]" {
t.Error(result)
}
result = tree.GetRange(50, 1)
if spew.Sprint(result) != "[40 30 17 13 10 5 2 1]" {
t.Error(result)
}
result = tree.GetRange(30, 20)
if spew.Sprint(result) != "[30]" {
t.Error(result)
}
}
func TestGetRange(t *testing.T) {
tree := New(compare.Int)
for _, v := range []int{5, 6, 8, 10, 13, 17, 1, 2, 40, 30} {
tree.Put(v)
}
// t.Error(tree.debugString())
// t.Error(tree.getArountNode(20))
// t.Error(tree.Values())
result := tree.GetRange(0, 20)
if spew.Sprint(result) != "[1 2 5 6 8 10 13 17]" {
t.Error(result)
}
result = tree.GetRange(-5, -1)
if spew.Sprint(result) != "[]" {
t.Error(result)
}
result = tree.GetRange(7, 20)
if spew.Sprint(result) != "[8 10 13 17]" {
t.Error(result)
}
result = tree.GetRange(30, 40)
if spew.Sprint(result) != "[30 40]" {
t.Error(result)
}
result = tree.GetRange(30, 60)
if spew.Sprint(result) != "[30 40]" {
t.Error(result)
}
result = tree.GetRange(40, 40)
if spew.Sprint(result) != "[40]" {
t.Error(result)
}
result = tree.GetRange(50, 60)
if spew.Sprint(result) != "[]" {
t.Error(result)
}
result = tree.GetRange(50, 1)
if spew.Sprint(result) != "[40 30 17 13 10 8 6 5 2 1]" {
t.Error(result)
}
result = tree.GetRange(30, 20)
if spew.Sprint(result) != "[30]" {
t.Error(result)
}
}
func TestTravalsal(t *testing.T) {
tree := New(compare.Int)
for _, v := range []int{5, 6, 8, 10, 13, 17, 1, 2, 40, 30} {
tree.Put(v)
}
i := 0
var result []interface{}
tree.Traversal(func(v interface{}) bool {
result = append(result, v)
i++
if i >= 10 {
return false
}
return true
})
if spew.Sprint(result) != "[1 2 5 6 8 10 13 17 30 40]" {
t.Error(result)
}
}
// func TestRemoveAll(t *testing.T) {
// ALL:
// for c := 0; c < 5000; c++ {
// tree := New(compare.Int)
// gods := avltree.NewWithIntComparator()
// var l []int
// m := make(map[int]int)
// for i := 0; len(l) < 50; i++ {
// v := randomdata.Number(0, 100000)
// if _, ok := m[v]; !ok {
// m[v] = v
// l = append(l, v)
// tree.Put(v, v)
// gods.Put(v, v)
// }
// }
// for i := 0; i < 50; i++ {
// tree.Remove(l[i])
// gods.Remove(l[i])
// s1 := spew.Sprint(tree.Values())
// s2 := spew.Sprint(gods.Values())
// if s1 != s2 {
// t.Error("avl remove error", "avlsize = ", tree.Size())
// t.Error(tree.root, i, l[i])
// t.Error(s1)
// t.Error(s2)
// break ALL
// }
// }
// }
// }
// func TestRemove(t *testing.T) {
// ALL:
// for N := 0; N < 5000; N++ {
// tree := New(compare.Int)
// gods := avltree.NewWithIntComparator()
// var l []int
// m := make(map[int]int)
// for i := 0; len(l) < 20; i++ {
// v := randomdata.Number(0, 100)
// if _, ok := m[v]; !ok {
// l = append(l, v)
// m[v] = v
// tree.Put(v, v)
// gods.Put(v, v)
// }
// }
// src1 := tree.String()
// src2 := gods.String()
// for i := 0; i < 20; i++ {
// tree.Remove(l[i])
// gods.Remove(l[i])
// if tree.root != nil && spew.Sprint(gods.Values()) != spew.Sprint(tree.Values()) {
// t.Error(src1)
// t.Error(src2)
// t.Error(tree.debugString())
// t.Error(gods.String())
// t.Error(l[i])
// break ALL
// }
// }
// }
// }
// func BenchmarkGetRange(b *testing.B) {
// }
// func BenchmarkIndexRange(b *testing.B) {
// tree := New(compare.Int)
// l := loadTestData()
// b.N = len(l)
// for _, v := range l {
// tree.Put(v, v)
// }
// b.ResetTimer()
// b.StartTimer()
// execCount := 5
// b.N = len(l) * execCount
// for i := 0; i < execCount; i++ {
// for range l {
// tree.IndexRange(i, i+49)
// }
// }
// }
// func BenchmarkSkipListGet(b *testing.B) {
// sl := skiplist.New(skiplist.Int)
// l := loadTestData()
// b.N = len(l)
// for _, v := range l {
// sl.Set(v, v)
// }
// b.ResetTimer()
// b.StartTimer()
// execCount := 5
// b.N = len(l) * execCount
// for i := 0; i < execCount; i++ {
// for _, v := range l {
// sl.Get(v)
// // e := sl.Get(v)
// // var result [50]interface{}
// // for i := 0; i < 50 && e != nil; i++ {
// // result[i] = e.Value
// // e = e.Next()
// // }
// }
// }
// }
// func BenchmarkSkipListSet(b *testing.B) {
// l := loadTestData()
// execCount := 1
// b.N = len(l) * execCount
// for i := 0; i < execCount; i++ {
// sl := skiplist.New(skiplist.Int)
// for _, v := range l {
// sl.Set(v, v)
// }
// }
// }
// func BenchmarkIterator(b *testing.B) {
// tree := New(compare.Int)
// l := loadTestData()
// b.N = len(l)
// for _, v := range l {
// tree.Put(v, v)
// }
// b.ResetTimer()
// b.StartTimer()
// iter := tree.Iterator()
// b.N = 0
// for iter.Next() {
// b.N++
// }
// for iter.Prev() {
// b.N++
// }
// for iter.Next() {
// b.N++
// }
// b.Log(b.N, len(l))
// }
// func BenchmarkRemove(b *testing.B) {
// tree := New(compare.Int)
// l := loadTestData()
// b.N = len(l)
// for _, v := range l {
// tree.Put(v, v)
// }
// b.ResetTimer()
// b.StartTimer()
// for i := 0; i < len(l); i++ {
// tree.Remove(l[i])
// }
// }
// func BenchmarkGodsRemove(b *testing.B) {
// tree := avltree.NewWithIntComparator()
// l := loadTestData()
// b.N = len(l)
// for _, v := range l {
// tree.Put(v, v)
// }
// b.ResetTimer()
// b.StartTimer()
// for i := 0; i < len(l); i++ {
// tree.Remove(l[i])
// }
// }
// func BenchmarkGodsRBRemove(b *testing.B) {
// tree := redblacktree.NewWithIntComparator()
// l := loadTestData()
// b.N = len(l)
// for _, v := range l {
// tree.Put(v, v)
// }
// b.ResetTimer()
// b.StartTimer()
// for i := 0; i < len(l); i++ {
// tree.Remove(l[i])
// }
// }
// func BenchmarkGet(b *testing.B) {
// tree := New(compare.Int)
// l := loadTestData()
// b.N = len(l)
// for i := 0; i < b.N; i++ {
// tree.Put(l[i], i)
// }
// b.ResetTimer()
// b.StartTimer()
// execCount := 10
// b.N = len(l) * execCount
// for i := 0; i < execCount; i++ {
// for _, v := range l {
// tree.Get(v)
// }
// }
// }
// func BenchmarkGodsRBGet(b *testing.B) {
// tree := redblacktree.NewWithIntComparator()
// l := loadTestData()
// b.N = len(l)
// for i := 0; i < b.N; i++ {
// tree.Put(l[i], i)
// }
// b.ResetTimer()
// b.StartTimer()
// execCount := 10
// b.N = len(l) * execCount
// for i := 0; i < execCount; i++ {
// for _, v := range l {
// tree.Get(v)
// }
// }
// }
// func BenchmarkGodsAvlGet(b *testing.B) {
// tree := avltree.NewWithIntComparator()
// l := loadTestData()
// b.N = len(l)
// for i := 0; i < b.N; i++ {
// tree.Put(l[i], i)
// }
// b.ResetTimer()
// b.StartTimer()
// execCount := 10
// b.N = len(l) * execCount
// for i := 0; i < execCount; i++ {
// for _, v := range l {
// tree.Get(v)
// }
// }
// }
// func BenchmarkPut(b *testing.B) {
// l := loadTestData()
// b.ResetTimer()
// b.StartTimer()
// execCount := 50
// b.N = len(l) * execCount
// for i := 0; i < execCount; i++ {
// tree := New(compare.Int)
// for _, v := range l {
// tree.Put(v, v)
// }
// }
// }
// func TestPutStable(t *testing.T) {
// }
// func BenchmarkGodsRBPut(b *testing.B) {
// l := loadTestData()
// b.ResetTimer()
// b.StartTimer()
// execCount := 50
// b.N = len(l) * execCount
// for i := 0; i < execCount; i++ {
// tree := redblacktree.NewWithIntComparator()
// for _, v := range l {
// tree.Put(v, v)
// }
// }
// }
// func BenchmarkGodsPut(b *testing.B) {
// tree := avltree.NewWithIntComparator()
// l := loadTestData()
// b.ResetTimer()
// b.StartTimer()
// b.N = len(l)
// for _, v := range l {
// tree.Put(v, v)
// }
// }

View File

@ -35,36 +35,13 @@ func (iter *Iterator) GetNode() *Node {
}
func (iter *Iterator) ToHead() {
if iter.cur == nil {
iter.cur = iter.up
for iter.Prev() {
}
for iter.cur.parent != nil {
iter.cur = iter.cur.parent
}
for iter.cur.children[0] != nil {
iter.cur = iter.cur.children[0]
}
iter.SetNode(iter.cur)
iter.cur = nil
}
func (iter *Iterator) ToTail() {
if iter.cur == nil {
iter.cur = iter.up
for iter.Next() {
}
for iter.cur.parent != nil {
iter.cur = iter.cur.parent
}
for iter.cur.children[1] != nil {
iter.cur = iter.cur.children[1]
}
iter.SetNode(iter.cur)
iter.cur = nil
}
func (iter *Iterator) SetNode(n *Node) {
@ -73,10 +50,6 @@ func (iter *Iterator) SetNode(n *Node) {
iter.tstack.Clear()
}
func (iter *Iterator) Key() interface{} {
return iter.cur.key
}
func (iter *Iterator) Value() interface{} {
return iter.cur.value
}

View File

@ -1,35 +0,0 @@
package vbtkey
import (
"sort"
"testing"
"github.com/474420502/focus/compare"
)
func TestIerator(t *testing.T) {
tree := New(compare.Int)
l := []int{5, 10, 100, 30, 40, 70, 45, 35, 23}
for _, v := range l {
tree.Put(v, v)
}
sort.Ints(l)
iter := tree.Iterator()
iter.ToHead()
for i := 0; iter.Next(); i++ {
if iter.Value() != l[i] {
t.Error(iter.Value(), l[i])
}
}
iter.ToTail()
iter.Prev()
for i := len(l) - 1; iter.Next(); i-- {
if iter.Value() != l[i] {
t.Error(iter.Value(), l[i])
}
}
}

View File

@ -27,7 +27,6 @@ func (n *Node) String() string {
return spew.Sprint(n.value) + "(" + p + "|" + spew.Sprint(n.size) + ")"
}
// Tree increasing
type Tree struct {
root *Node
Compare compare.Compare
@ -44,7 +43,7 @@ func New(Compare compare.Compare) *Tree {
}
func (tree *Tree) String() string {
str := "VBTree-Key\n"
str := "AVLTree\n"
if tree.root == nil {
return str + "nil"
}
@ -63,7 +62,7 @@ func (tree *Tree) Size() int {
return tree.root.size
}
func (tree *Tree) IndexNode(idx int) *Node {
func (tree *Tree) indexNode(idx int) *Node {
cur := tree.root
if idx >= 0 {
for cur != nil {
@ -95,7 +94,7 @@ func (tree *Tree) IndexNode(idx int) *Node {
}
func (tree *Tree) Index(idx int) (interface{}, bool) {
n := tree.IndexNode(idx)
n := tree.indexNode(idx)
if n != nil {
return n.value, true
}
@ -119,7 +118,7 @@ func (tree *Tree) IndexRange(idx1, idx2 int) (result []interface{}, ok bool) { /
ok = false
}
n := tree.IndexNode(idx1)
n := tree.indexNode(idx1)
tree.iter.SetNode(n)
iter := tree.iter
result = make([]interface{}, 0, idx1-idx2)
@ -141,7 +140,7 @@ func (tree *Tree) IndexRange(idx1, idx2 int) (result []interface{}, ok bool) { /
ok = false
}
if n := tree.IndexNode(idx1); n != nil {
if n := tree.indexNode(idx1); n != nil {
tree.iter.SetNode(n)
iter := tree.iter
result = make([]interface{}, 0, idx2-idx1)
@ -163,15 +162,15 @@ func (tree *Tree) IndexRange(idx1, idx2 int) (result []interface{}, ok bool) { /
}
func (tree *Tree) RemoveIndex(idx int) (interface{}, bool) {
n := tree.IndexNode(idx)
n := tree.indexNode(idx)
if n != nil {
tree.RemoveNode(n)
tree.removeNode(n)
return n.value, true
}
return nil, false
}
func (tree *Tree) RemoveNode(n *Node) {
func (tree *Tree) removeNode(n *Node) {
if tree.root.size == 1 {
tree.root = nil
// return n
@ -232,7 +231,7 @@ func (tree *Tree) RemoveNode(n *Node) {
func (tree *Tree) Remove(key interface{}) (interface{}, bool) {
if n, ok := tree.GetNode(key); ok {
tree.RemoveNode(n)
tree.removeNode(n)
return n.value, true
}
// return nil
@ -348,7 +347,7 @@ func (tree *Tree) getArountNode(key interface{}) (result [3]*Node) {
for n := tree.root; n != nil; {
last = n
c := tree.Compare(key, n.key)
c := tree.Compare(key, n.value)
switch c {
case -1:
n = n.children[0]

View File

@ -66,7 +66,7 @@ func TestLargePushRemove(t *testing.T) {
}
tree.Clear()
if tree.String() != "VBTree-Key\nnil" {
if tree.String() != "AVLTree\nnil" {
t.Error("tree String is error")
}
}

View File

@ -1,252 +0,0 @@
package vbtkeydup
import (
lastack "github.com/474420502/focus/stack/listarraystack"
)
type Iterator struct {
dir int
up *Node
cur *Node
tstack *lastack.Stack
// curnext *Node
}
func initIterator(avltree *Tree) *Iterator {
iter := &Iterator{tstack: lastack.New()}
iter.up = avltree.root
return iter
}
func NewIterator(n *Node) *Iterator {
iter := &Iterator{tstack: lastack.New()}
iter.up = n
return iter
}
func NewIteratorWithCap(n *Node, cap int) *Iterator {
iter := &Iterator{tstack: lastack.NewWithCap(cap)}
iter.up = n
return iter
}
func (iter *Iterator) GetNode() *Node {
return iter.cur
}
func (iter *Iterator) ToHead() {
if iter.cur == nil {
iter.cur = iter.up
}
for iter.cur.parent != nil {
iter.cur = iter.cur.parent
}
for iter.cur.children[0] != nil {
iter.cur = iter.cur.children[0]
}
iter.SetNode(iter.cur)
iter.cur = nil
}
func (iter *Iterator) ToTail() {
if iter.cur == nil {
iter.cur = iter.up
}
for iter.cur.parent != nil {
iter.cur = iter.cur.parent
}
for iter.cur.children[1] != nil {
iter.cur = iter.cur.children[1]
}
iter.SetNode(iter.cur)
iter.cur = nil
}
func (iter *Iterator) SetNode(n *Node) {
iter.up = n
iter.dir = 0
iter.tstack.Clear()
}
func (iter *Iterator) Key() interface{} {
return iter.cur.key
}
func (iter *Iterator) Value() interface{} {
return iter.cur.value
}
func (iter *Iterator) GetNext(cur *Node, idx int) *Node {
// iter := NewIterator(cur)
iter.SetNode(cur)
iter.curPushNextStack(iter.up)
iter.up = iter.getNextUp(iter.up)
for i := 0; i < idx; i++ {
if iter.tstack.Size() == 0 {
if iter.up == nil {
return nil
}
iter.tstack.Push(iter.up)
iter.up = iter.getNextUp(iter.up)
}
if v, ok := iter.tstack.Pop(); ok {
iter.cur = v.(*Node)
if i == idx-1 {
return iter.cur
}
iter.curPushNextStack(iter.cur)
} else {
return nil
}
}
return cur
}
func (iter *Iterator) Next() (result bool) {
if iter.dir > -1 {
if iter.dir == 1 && iter.cur != nil {
iter.tstack.Clear()
iter.curPushNextStack(iter.cur)
iter.up = iter.getNextUp(iter.cur)
}
iter.dir = -1
}
if iter.tstack.Size() == 0 {
if iter.up == nil {
return false
}
iter.tstack.Push(iter.up)
iter.up = iter.getNextUp(iter.up)
}
if v, ok := iter.tstack.Pop(); ok {
iter.cur = v.(*Node)
iter.curPushNextStack(iter.cur)
return true
}
return false
}
func (iter *Iterator) GetPrev(cur *Node, idx int) *Node {
// iter := NewIterator(cur)
iter.SetNode(cur)
iter.curPushPrevStack(iter.up)
iter.up = iter.getPrevUp(iter.up)
for i := 0; i < idx; i++ {
if iter.tstack.Size() == 0 {
if iter.up == nil {
return nil
}
iter.tstack.Push(iter.up)
iter.up = iter.getPrevUp(iter.up)
}
if v, ok := iter.tstack.Pop(); ok {
iter.cur = v.(*Node)
if i == idx-1 {
return iter.cur
}
iter.curPushPrevStack(iter.cur)
} else {
return nil
}
}
return cur
}
func (iter *Iterator) Prev() (result bool) {
if iter.dir < 1 { // 非 1(next 方向定义 -1 为 prev)
if iter.dir == -1 && iter.cur != nil { // 如果上次为prev方向, 则清空辅助计算的栈
iter.tstack.Clear()
iter.curPushPrevStack(iter.cur) // 把当前cur计算的回朔
iter.up = iter.getPrevUp(iter.cur) // cur 寻找下个要计算up
}
iter.dir = 1
}
// 如果栈空了, 把up的递归计算入栈, 重新计算 下次的up值
if iter.tstack.Size() == 0 {
if iter.up == nil {
return false
}
iter.tstack.Push(iter.up)
iter.up = iter.getPrevUp(iter.up)
}
if v, ok := iter.tstack.Pop(); ok {
iter.cur = v.(*Node)
iter.curPushPrevStack(iter.cur)
return true
}
// 如果再次计算的栈为空, 则只能返回false
return false
}
func getRelationship(cur *Node) int {
if cur.parent.children[1] == cur {
return 1
}
return 0
}
func (iter *Iterator) getPrevUp(cur *Node) *Node {
for cur.parent != nil {
if getRelationship(cur) == 1 { // next 在 降序 小值. 如果child在右边, parent 比 child 小, parent才有效, 符合降序
return cur.parent
}
cur = cur.parent
}
return nil
}
func (iter *Iterator) curPushPrevStack(cur *Node) {
Prev := cur.children[0] // 当前的左然后向右找, 找到最大, 就是最接近cur 并且小于cur的值
if Prev != nil {
iter.tstack.Push(Prev)
for Prev.children[1] != nil {
Prev = Prev.children[1]
iter.tstack.Push(Prev) // 入栈 用于回溯
}
}
}
func (iter *Iterator) getNextUp(cur *Node) *Node {
for cur.parent != nil {
if getRelationship(cur) == 0 { // Prev 在 降序 大值. 如果child在左边, parent 比 child 大, parent才有效 , 符合降序
return cur.parent
}
cur = cur.parent
}
return nil
}
func (iter *Iterator) curPushNextStack(cur *Node) {
next := cur.children[1]
if next != nil {
iter.tstack.Push(next)
for next.children[0] != nil {
next = next.children[0]
iter.tstack.Push(next)
}
}
}

View File

@ -1,35 +0,0 @@
package vbtkeydup
import (
"sort"
"testing"
"github.com/474420502/focus/compare"
)
func TestIerator(t *testing.T) {
tree := New(compare.Int)
l := []int{5, 10, 100, 30, 40, 70, 45, 35, 23}
for _, v := range l {
tree.Put(v, v)
}
sort.Ints(l)
iter := tree.Iterator()
iter.ToHead()
for i := 0; iter.Next(); i++ {
if iter.Value() != l[i] {
t.Error(iter.Value(), l[i])
}
}
iter.ToTail()
iter.Prev()
for i := len(l) - 1; iter.Next(); i-- {
if iter.Value() != l[i] {
t.Error(iter.Value(), l[i])
}
}
}

File diff suppressed because it is too large Load Diff

View File

@ -1,844 +0,0 @@
package vbtkeydup
import (
"bytes"
"encoding/gob"
"io/ioutil"
"log"
"sort"
"testing"
"github.com/Pallinder/go-randomdata"
"github.com/davecgh/go-spew/spew"
"github.com/474420502/focus/compare"
)
func loadTestData() []int {
data, err := ioutil.ReadFile("../l.log")
if err != nil {
log.Println(err)
}
var l []int
decoder := gob.NewDecoder(bytes.NewReader(data))
decoder.Decode(&l)
return l
}
func TestIteratorHeadTail(t *testing.T) {
tree := New(compare.Int)
l := []int{1, 7, 14, 14, 16, 17, 20, 30, 21, 40, 50, 3, 40, 40, 40, 15, 100}
for _, v := range l {
tree.Put(v, v)
}
iter := tree.Iterator()
iter.ToHead() // 从小到大
iter.Next()
if iter.Value() != 1 {
t.Error("value error", iter.Value())
}
iter.ToTail()
iter.Prev()
if iter.Value() != 100 {
t.Error("value error", iter.Value())
}
for n := 0; n < 500; n++ {
tree := New(compare.Int)
var results []int
for i := 0; i < 50; i++ {
v := randomdata.Number(0, 5000)
if ok := tree.Put(v, v); ok {
results = append(results, v)
}
}
result := tree.GetAround(5001)
iter = tree.Iterator()
iter.ToTail()
iter.Prev()
if iter.Value() != result[0] {
t.Error("ToTail error", result, iter.Value())
}
result = tree.GetAround(-1)
iter.ToHead()
iter.Next()
if iter.Value() != result[2] {
t.Error("ToTail error", result, iter.Value())
}
}
}
func TestLargePushRemove(t *testing.T) {
for n := 0; n < 10; n++ {
tree := New(compare.Int)
var results []int
for i := 0; i < 50000; i++ {
v := randomdata.Number(0, 100000000)
if ok := tree.Put(v, v); ok {
results = append(results, v)
}
}
if tree.Size() != len(results) {
t.Error("Szie error", tree.Size(), len(results))
}
for i := 0; i < len(results)-10; i++ {
tree.Remove(results[i])
}
results = results[len(results)-10:]
if tree.Size() != 10 {
t.Error("Szie error")
}
sort.Slice(results, func(i, j int) bool {
if results[i] < results[j] {
return true
}
return false
})
if spew.Sprint(results) != spew.Sprint(tree.Values()) {
t.Error("tree is error")
}
for i := 0; i < 10; i++ {
v1 := results[i]
v2, ok := tree.Index(i)
if !ok {
t.Error("not ok")
}
if v1 != v2 {
t.Error("v1(", v1, ") != v2(", v2, ")??")
}
}
tree.Clear()
if tree.String() != "VBTree-Dup\nnil" {
t.Error("tree String is error")
}
}
}
func TestRemoveIndex(t *testing.T) {
tree := New(compare.Int)
l := []int{7, 14, 14, 14, 16, 1, 40, 15}
for _, v := range l {
tree.Put(v, v)
}
// [1 7 14 14 14 15 16 40]
var result string
result = spew.Sprint(tree.Values())
if result != "[1 7 14 15 16 40]" {
t.Error("result = ", result, " should be [1 7 14 15 16 40]")
}
tree.RemoveIndex(3)
result = spew.Sprint(tree.Values())
if result != "[1 7 14 16 40]" {
t.Error("result is error")
}
tree.RemoveIndex(-1)
result = spew.Sprint(tree.Values())
if result != "[1 7 14 16]" {
t.Error("result is error")
}
tree.RemoveIndex(0)
result = spew.Sprint(tree.Values())
if result != "[7 14 16]" {
t.Error("result is error")
}
if tree.Size() != 3 {
t.Error("size is error")
}
for tree.Size() != 0 {
tree.RemoveIndex(0)
}
if tree.root != nil {
t.Error("tree roor is not error")
}
}
func TestIndexRange(t *testing.T) {
tree := New(compare.Int)
l := []int{7, 14, 14, 14, 16, 17, 20, 30, 21, 40, 50, 3, 40, 40, 40, 15}
for _, v := range l {
tree.Put(v, v)
}
// [3 7 14 15 16 17 20 21 30 40 50]
// t.Error(tree.Values(), tree.Size())
// t.Error(tree.debugString())
var result string
result = spew.Sprint(tree.IndexRange(0, 5))
if result != "[3 7 14 15 16 17] true" {
t.Error(result)
}
result = spew.Sprint(tree.IndexRange(2, 5))
if result != "[14 15 16 17] true" {
t.Error(result)
}
result = spew.Sprint(tree.IndexRange(5, 100))
if result != "[17 20 21 30 40 50] false" {
t.Error(result)
}
result = spew.Sprint(tree.IndexRange(10, 0)) // size = 11, index max = 10
if result != "[50 40 30 21 20 17 16 15 14 7 3] true" {
t.Error(result)
}
result = spew.Sprint(tree.IndexRange(11, 0)) // size = 11, index max = 10
if result != "[50 40 30 21 20 17 16 15 14 7 3] false" {
t.Error(result)
}
result = spew.Sprint(tree.IndexRange(4, 1)) // size = 11, index max = 10
if result != "[16 15 14 7] true" {
t.Error(result)
}
result = spew.Sprint(tree.IndexRange(-1, -5)) // size = 11, index max = 10
if result != "[50 40 30 21 20] true" {
t.Error(result)
}
result = spew.Sprint(tree.IndexRange(-1, -11)) // size = 11, index max = 0 - 10 (-1,-11)
if result != "[50 40 30 21 20 17 16 15 14 7 3] true" {
t.Error(result)
}
result = spew.Sprint(tree.IndexRange(-1, -12)) // size = 11, index max = 0 - 10 (-1,-11)
if result != "[50 40 30 21 20 17 16 15 14 7 3] false" {
t.Error(result)
}
result = spew.Sprint(tree.IndexRange(-5, -1)) // size = 11, index max = 0 - 10 (-1,-11)
if result != "[20 21 30 40 50] true" {
t.Error(result)
}
// [3 7 14 15 16 17 20 21 30 40 50]
result = spew.Sprint(tree.IndexRange(-5, 5)) //
if result != "[20 17] true" {
t.Error(result)
}
result = spew.Sprint(tree.IndexRange(5, -5)) //
if result != "[17 20] true" {
t.Error(result)
}
result = spew.Sprint(tree.IndexRange(-1, 6)) //
if result != "[50 40 30 21 20] true" {
t.Error(result)
}
}
func TestGetAround(t *testing.T) {
tree := New(compare.Int)
for _, v := range []int{7, 14, 14, 14, 16, 17, 20, 30, 21, 40, 50, 3, 40, 40, 40, 15} {
tree.Put(v, v)
}
var Result string
Result = spew.Sprint(tree.GetAround(17))
if Result != "[16 17 20]" {
t.Error(tree.Values())
t.Error("17 is root, tree.GetAround(17)) is error", Result)
t.Error(tree.debugString())
}
Result = spew.Sprint(tree.GetAround(3))
if Result != "[<nil> 3 7]" {
t.Error(tree.Values())
t.Error("tree.GetAround(3)) is error", Result)
t.Error(tree.debugString())
}
Result = spew.Sprint(tree.GetAround(40))
if Result != "[30 40 50]" {
t.Error(tree.Values())
t.Error("tree.GetAround(40)) is error", Result)
t.Error(tree.debugString())
}
Result = spew.Sprint(tree.GetAround(50))
if Result != "[40 50 <nil>]" {
t.Error(tree.Values())
t.Error("tree.GetAround(50)) is error", Result)
t.Error(tree.debugString())
}
Result = spew.Sprint(tree.GetAround(18))
if Result != "[17 <nil> 20]" {
t.Error(tree.Values())
t.Error("18 is not in list, tree.GetAround(18)) is error", Result)
t.Error(tree.debugString())
}
Result = spew.Sprint(tree.GetAround(5))
if Result != "[3 <nil> 7]" {
t.Error(tree.Values())
t.Error("5 is not in list, tree.GetAround(5)) is error", Result)
t.Error(tree.debugString())
}
Result = spew.Sprint(tree.GetAround(2))
if Result != "[<nil> <nil> 3]" {
t.Error(tree.Values())
t.Error("2 is not in list, tree.GetAround(2)) is error", Result)
t.Error(tree.debugString())
}
Result = spew.Sprint(tree.GetAround(100))
if Result != "[50 <nil> <nil>]" {
t.Error(tree.Values())
t.Error("50 is not in list, tree.GetAround(50)) is error", Result)
t.Error(tree.debugString())
}
}
// // for test error case
// func TestPutComparatorRandom(t *testing.T) {
// for n := 0; n < 300000; n++ {
// tree := New(compare.Int)
// godsavl := avltree.NewWithIntComparator()
// content := ""
// m := make(map[int]int)
// for i := 0; len(m) < 10; i++ {
// v := randomdata.Number(0, 65535)
// if _, ok := m[v]; !ok {
// m[v] = v
// content += spew.Sprint(v) + ","
// tree.Put(v, v)
// godsavl.Put(v, v)
// }
// }
// s1 := spew.Sprint(tree.Values())
// s2 := spew.Sprint(godsavl.Values())
// if s1 != s2 {
// t.Error(godsavl.String())
// t.Error(tree.debugString())
// t.Error(content, n)
// break
// }
// }
// }
func TestGet(t *testing.T) {
tree := New(compare.Int)
for _, v := range []int{2383, 7666, 3055, 39016, 57092, 27897, 36513, 1562, 22574, 23202} {
tree.Put(v, v)
}
for _, v := range []int{2383, 7666, 3055, 39016, 57092, 27897, 36513, 1562, 22574, 23202} {
v, ok := tree.Get(v)
if !ok {
t.Error("the val not found ", v)
}
}
if v, ok := tree.Get(10000); ok {
t.Error("the val(1000) is not in tree, but is found", v)
}
}
func TestDupGetRange(t *testing.T) {
tree := New(compare.Int)
for _, v := range []int{5, 10, 13, 5, 17, 1, 2, 10, 40, 30, 1} {
tree.Put(v, v)
}
result := tree.GetRange(0, 20)
if spew.Sprint(result) != "[1 2 5 10 13 17]" {
t.Error(result)
}
result = tree.GetRange(0, 8)
if spew.Sprint(result) != "[1 2 5]" {
t.Error(result)
}
result = tree.GetRange(-5, -1)
if spew.Sprint(result) != "[]" {
t.Error(result)
}
result = tree.GetRange(7, 20)
if spew.Sprint(result) != "[10 13 17]" {
t.Error(result)
}
result = tree.GetRange(30, 40)
if spew.Sprint(result) != "[30 40]" {
t.Error(result)
}
result = tree.GetRange(30, 60)
if spew.Sprint(result) != "[30 40]" {
t.Error(result)
}
result = tree.GetRange(40, 40)
if spew.Sprint(result) != "[40]" {
t.Error(result)
}
result = tree.GetRange(50, 60)
if spew.Sprint(result) != "[]" {
t.Error(result)
}
result = tree.GetRange(50, 1)
if spew.Sprint(result) != "[40 30 17 13 10 5 2 1]" {
t.Error(result)
}
result = tree.GetRange(30, 20)
if spew.Sprint(result) != "[30]" {
t.Error(result)
}
}
func TestGetRange(t *testing.T) {
tree := New(compare.Int)
for _, v := range []int{5, 6, 8, 10, 13, 17, 1, 2, 40, 30} {
tree.Put(v, v)
}
// t.Error(tree.debugString())
// t.Error(tree.getArountNode(20))
// t.Error(tree.Values())
result := tree.GetRange(0, 20)
if spew.Sprint(result) != "[1 2 5 6 8 10 13 17]" {
t.Error(result)
}
result = tree.GetRange(-5, -1)
if spew.Sprint(result) != "[]" {
t.Error(result)
}
result = tree.GetRange(7, 20)
if spew.Sprint(result) != "[8 10 13 17]" {
t.Error(result)
}
result = tree.GetRange(30, 40)
if spew.Sprint(result) != "[30 40]" {
t.Error(result)
}
result = tree.GetRange(30, 60)
if spew.Sprint(result) != "[30 40]" {
t.Error(result)
}
result = tree.GetRange(40, 40)
if spew.Sprint(result) != "[40]" {
t.Error(result)
}
result = tree.GetRange(50, 60)
if spew.Sprint(result) != "[]" {
t.Error(result)
}
result = tree.GetRange(50, 1)
if spew.Sprint(result) != "[40 30 17 13 10 8 6 5 2 1]" {
t.Error(result)
}
result = tree.GetRange(30, 20)
if spew.Sprint(result) != "[30]" {
t.Error(result)
}
}
func TestTravalsal(t *testing.T) {
tree := New(compare.Int)
for _, v := range []int{5, 6, 8, 10, 13, 17, 1, 2, 40, 30} {
tree.Put(v, v)
}
i := 0
var result []interface{}
tree.Traversal(func(k, v interface{}) bool {
result = append(result, k)
i++
if i >= 10 {
return false
}
return true
})
if spew.Sprint(result) != "[1 2 5 6 8 10 13 17 30 40]" {
t.Error(result)
}
}
// func TestRemoveAll(t *testing.T) {
// ALL:
// for c := 0; c < 5000; c++ {
// tree := New(compare.Int)
// gods := avltree.NewWithIntComparator()
// var l []int
// m := make(map[int]int)
// for i := 0; len(l) < 50; i++ {
// v := randomdata.Number(0, 100000)
// if _, ok := m[v]; !ok {
// m[v] = v
// l = append(l, v)
// tree.Put(v, v)
// gods.Put(v, v)
// }
// }
// for i := 0; i < 50; i++ {
// tree.Remove(l[i])
// gods.Remove(l[i])
// s1 := spew.Sprint(tree.Values())
// s2 := spew.Sprint(gods.Values())
// if s1 != s2 {
// t.Error("avl remove error", "avlsize = ", tree.Size())
// t.Error(tree.root, i, l[i])
// t.Error(s1)
// t.Error(s2)
// break ALL
// }
// }
// }
// }
// func TestRemove(t *testing.T) {
// ALL:
// for N := 0; N < 5000; N++ {
// tree := New(compare.Int)
// gods := avltree.NewWithIntComparator()
// var l []int
// m := make(map[int]int)
// for i := 0; len(l) < 20; i++ {
// v := randomdata.Number(0, 100)
// if _, ok := m[v]; !ok {
// l = append(l, v)
// m[v] = v
// tree.Put(v, v)
// gods.Put(v, v)
// }
// }
// src1 := tree.String()
// src2 := gods.String()
// for i := 0; i < 20; i++ {
// tree.Remove(l[i])
// gods.Remove(l[i])
// if tree.root != nil && spew.Sprint(gods.Values()) != spew.Sprint(tree.Values()) {
// t.Error(src1)
// t.Error(src2)
// t.Error(tree.debugString())
// t.Error(gods.String())
// t.Error(l[i])
// break ALL
// }
// }
// }
// }
// func BenchmarkGetRange(b *testing.B) {
// }
// func BenchmarkIndexRange(b *testing.B) {
// tree := New(compare.Int)
// l := loadTestData()
// b.N = len(l)
// for _, v := range l {
// tree.Put(v, v)
// }
// b.ResetTimer()
// b.StartTimer()
// execCount := 5
// b.N = len(l) * execCount
// for i := 0; i < execCount; i++ {
// for range l {
// tree.IndexRange(i, i+49)
// }
// }
// }
// func BenchmarkSkipListGet(b *testing.B) {
// sl := skiplist.New(skiplist.Int)
// l := loadTestData()
// b.N = len(l)
// for _, v := range l {
// sl.Set(v, v)
// }
// b.ResetTimer()
// b.StartTimer()
// execCount := 5
// b.N = len(l) * execCount
// for i := 0; i < execCount; i++ {
// for _, v := range l {
// sl.Get(v)
// // e := sl.Get(v)
// // var result [50]interface{}
// // for i := 0; i < 50 && e != nil; i++ {
// // result[i] = e.Value
// // e = e.Next()
// // }
// }
// }
// }
// func BenchmarkSkipListSet(b *testing.B) {
// l := loadTestData()
// execCount := 1
// b.N = len(l) * execCount
// for i := 0; i < execCount; i++ {
// sl := skiplist.New(skiplist.Int)
// for _, v := range l {
// sl.Set(v, v)
// }
// }
// }
// func BenchmarkIterator(b *testing.B) {
// tree := New(compare.Int)
// l := loadTestData()
// b.N = len(l)
// for _, v := range l {
// tree.Put(v, v)
// }
// b.ResetTimer()
// b.StartTimer()
// iter := tree.Iterator()
// b.N = 0
// for iter.Next() {
// b.N++
// }
// for iter.Prev() {
// b.N++
// }
// for iter.Next() {
// b.N++
// }
// b.Log(b.N, len(l))
// }
// func BenchmarkRemove(b *testing.B) {
// tree := New(compare.Int)
// l := loadTestData()
// b.N = len(l)
// for _, v := range l {
// tree.Put(v, v)
// }
// b.ResetTimer()
// b.StartTimer()
// for i := 0; i < len(l); i++ {
// tree.Remove(l[i])
// }
// }
// func BenchmarkGodsRemove(b *testing.B) {
// tree := avltree.NewWithIntComparator()
// l := loadTestData()
// b.N = len(l)
// for _, v := range l {
// tree.Put(v, v)
// }
// b.ResetTimer()
// b.StartTimer()
// for i := 0; i < len(l); i++ {
// tree.Remove(l[i])
// }
// }
// func BenchmarkGodsRBRemove(b *testing.B) {
// tree := redblacktree.NewWithIntComparator()
// l := loadTestData()
// b.N = len(l)
// for _, v := range l {
// tree.Put(v, v)
// }
// b.ResetTimer()
// b.StartTimer()
// for i := 0; i < len(l); i++ {
// tree.Remove(l[i])
// }
// }
// func BenchmarkGet(b *testing.B) {
// tree := New(compare.Int)
// l := loadTestData()
// b.N = len(l)
// for i := 0; i < b.N; i++ {
// tree.Put(l[i], i)
// }
// b.ResetTimer()
// b.StartTimer()
// execCount := 10
// b.N = len(l) * execCount
// for i := 0; i < execCount; i++ {
// for _, v := range l {
// tree.Get(v)
// }
// }
// }
// func BenchmarkGodsRBGet(b *testing.B) {
// tree := redblacktree.NewWithIntComparator()
// l := loadTestData()
// b.N = len(l)
// for i := 0; i < b.N; i++ {
// tree.Put(l[i], i)
// }
// b.ResetTimer()
// b.StartTimer()
// execCount := 10
// b.N = len(l) * execCount
// for i := 0; i < execCount; i++ {
// for _, v := range l {
// tree.Get(v)
// }
// }
// }
// func BenchmarkGodsAvlGet(b *testing.B) {
// tree := avltree.NewWithIntComparator()
// l := loadTestData()
// b.N = len(l)
// for i := 0; i < b.N; i++ {
// tree.Put(l[i], i)
// }
// b.ResetTimer()
// b.StartTimer()
// execCount := 10
// b.N = len(l) * execCount
// for i := 0; i < execCount; i++ {
// for _, v := range l {
// tree.Get(v)
// }
// }
// }
// func BenchmarkPut(b *testing.B) {
// l := loadTestData()
// b.ResetTimer()
// b.StartTimer()
// execCount := 50
// b.N = len(l) * execCount
// for i := 0; i < execCount; i++ {
// tree := New(compare.Int)
// for _, v := range l {
// tree.Put(v, v)
// }
// }
// }
// func TestPutStable(t *testing.T) {
// }
// func BenchmarkGodsRBPut(b *testing.B) {
// l := loadTestData()
// b.ResetTimer()
// b.StartTimer()
// execCount := 50
// b.N = len(l) * execCount
// for i := 0; i < execCount; i++ {
// tree := redblacktree.NewWithIntComparator()
// for _, v := range l {
// tree.Put(v, v)
// }
// }
// }
// func BenchmarkGodsPut(b *testing.B) {
// tree := avltree.NewWithIntComparator()
// l := loadTestData()
// b.ResetTimer()
// b.StartTimer()
// b.N = len(l)
// for _, v := range l {
// tree.Put(v, v)
// }
// }

View File

@ -3,7 +3,6 @@ package utils
var bit = uint(32 << (^uint(0) >> 63))
var bitsub1 = bit - 1
// AbsInt
func AbsInt(n int) uint {
y := n >> bitsub1
return uint((n ^ y) - y)