Skip to content

Instantly share code, notes, and snippets.

@ancientlore
Created February 7, 2014 00:10
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ancientlore/8855122 to your computer and use it in GitHub Desktop.
Save ancientlore/8855122 to your computer and use it in GitHub Desktop.
go-avltree sample code
package main
import (
"os"
"fmt"
"rand"
"github.com/ancientlore/go-avltree"
)
func compareString(a interface{}, b interface{}) int {
if a.(string) < b.(string) {
return -1
} else if a.(string) > b.(string) {
return 1
}
return 0
}
func compareInt(a interface{}, b interface{}) int {
if a.(int) < b.(int) {
return -1
} else if a.(int) > b.(int) {
return 1
}
return 0
}
func testCompareInt(a interface{}, b interface{}) int {
if a.(int) < b.(int) {
return -1
} else if a.(int) > b.(int) {
return 1
}
return 0
}
func printString(s interface{}) { fmt.Printf("%-8.8s", s.(string)) }
func main() {
t := avltree.New(compareString, avltree.AllowDuplicates)
s := []string{
"Dharmesh", "Andy", "Sriram", "John", "Daniel",
"Michael", "Yadira", "Awez", "Robert", "Greg",
"Steve", "Glen", "Rahul", "Piotr", "Gigi",
}
for i := range (s) {
// fmt.Printf("Adding string at position %d: %s\n", i, s[i]);
t.Add(s[i])
}
t.Print(os.Stdout, printString, 8)
t.RemoveAt(5)
t.Print(os.Stdout, printString, 8)
var x []interface{}
x = t.Data()
for i := range (x) {
fmt.Printf("%s\n", x[i])
}
t.Remove("Rahul")
t.Print(os.Stdout, printString, 8)
t.Clear()
for j := 0; j < 100; j++ {
for i := range (s) {
t.Add(s[i])
}
}
fmt.Printf("Added %d items\n", 100*len(s))
fmt.Printf("Tree contains %d items, could hold %d with the same height of %d\n", t.Len(), t.Cap(), t.Height())
t.Clear()
fmt.Printf("Tree contains %d items, could hold %d with the same height of %d\n", t.Len(), t.Cap(), t.Height())
t.Add("foo")
fmt.Printf("Tree contains %d items, could hold %d with the same height of %d\n", t.Len(), t.Cap(), t.Height())
t.Add("bar")
fmt.Printf("Tree contains %d items, could hold %d with the same height of %d\n", t.Len(), t.Cap(), t.Height())
t.Init(testCompareInt, avltree.AllowDuplicates)
for j := 0; j < 100000; j++ {
t.Add(rand.Int())
}
fmt.Printf("Tree contains %d items, could hold %d with the same height of %d\n", t.Len(), t.Cap(), t.Height())
t.Clear()
for j := 0; j < 100000; j++ {
t.Add(j)
}
fmt.Printf("Tree contains %d items, could hold %d with the same height of %d\n", t.Len(), t.Cap(), t.Height())
sm := 0
t.Do(func(z interface{}) { sm += z.(int) })
fmt.Printf("Sum is %d\n", sm);
t.Do(func(z interface{}) { if z.(int) % 3333 == 0 { fmt.Printf("%d ", z); } })
fmt.Printf("\n");
for v := range t.Iter() {
if v.(int) % 3333 == 0 {
fmt.Printf("%d ", v);
}
}
fmt.Printf("\n");
}
@aletheia7
Copy link

Line 48 contains "for i := range (s) {." I am curious as to why the variable s is contained in parenthesis?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment