Commit 79ae16b

bryfry <bryon@fryer.io>
2025-01-19 17:38:58
cleanup
1 parent 8b303dd
galaxy.go
@@ -0,0 +1,45 @@
+package main
+
+import "gonum.org/v1/gonum/spatial/kdtree"
+
+type galaxy []Location
+
+func (g galaxy) Len() int                              { return len(g) }
+func (g galaxy) Index(i int) kdtree.Comparable         { return g[i] }
+func (g galaxy) Slice(start, end int) kdtree.Interface { return g[start:end] }
+func (g galaxy) Pivot(d kdtree.Dim) int {
+	return plane{galaxy: g, Dim: d}.Pivot()
+}
+
+type plane struct {
+	kdtree.Dim
+	galaxy
+}
+
+func (p plane) Less(i, j int) bool {
+	switch p.Dim {
+	case 0:
+		return p.galaxy[i].a < p.galaxy[j].a
+	case 1:
+		return p.galaxy[i].e < p.galaxy[j].e
+	case 2:
+		return p.galaxy[i].m < p.galaxy[j].m
+	case 3:
+		return p.galaxy[i].v < p.galaxy[j].v
+	default:
+		panic("illegal dimension")
+	}
+}
+
+func (p plane) Pivot() int {
+	return kdtree.Partition(p, kdtree.MedianOfMedians(p))
+}
+
+func (p plane) Slice(start, end int) kdtree.SortSlicer {
+	p.galaxy = p.galaxy[start:end]
+	return p
+}
+
+func (p plane) Swap(i, j int) {
+	p.galaxy[i], p.galaxy[j] = p.galaxy[j], p.galaxy[i]
+}
location.go
@@ -15,8 +15,8 @@ type Location struct {
 	v uint16
 }
 
-func NewLocation() *Location {
-	return &Location{
+func NewLocation() Location {
+	return Location{
 		a: uint16(rand.UintN(1 << 16)),
 		e: uint16(rand.UintN(1 << 16)),
 		m: uint16(rand.UintN(1 << 16)),
@@ -24,7 +24,7 @@ func NewLocation() *Location {
 	}
 }
 
-func (l *Location) String() string {
+func (l Location) String() string {
 	return fmt.Sprintf("%04X:%04X:%04X:%04X",
 		l.a, l.e, l.m, l.v)
 }
main.go
@@ -1,13 +1,27 @@
 package main
 
 import (
+	"fmt"
+	"math"
+
 	"gonum.org/v1/gonum/spatial/kdtree"
 )
 
 func main() {
-	var galaxy []*Location = make([]*Location, 100)
-	for _ = range 100 {
-		galaxy = append(galaxy, NewLocation())
+	var g galaxy = make([]Location, 1000)
+	for range 100 {
+		l := NewLocation()
+		fmt.Println(l)
+		g = append(g, l)
+	}
+	t := kdtree.New(g, false)
+	me := NewLocation()
+	keep := kdtree.NewNKeeper(5)
+	t.NearestSet(keep, me)
+
+	fmt.Println(me)
+	for _, l := range keep.Heap {
+		system := l.Comparable.(Location)
+		fmt.Printf("\t%s: %0.3f\n", system.String(), math.Sqrt(system.Distance(me)))
 	}
-	t := kdtree.New(galaxy, false)
 }