| 1 |
d. |
| 2 |
|
| 3 |
|
| 4 |
|
| 5 |
package kdtree |
| 6 |
|
| 7 |
var ( |
| 8 |
_ Interface = nbPoints{} |
| 9 |
_ Comparable = nbPoint{} |
| 10 |
) |
| 11 |
|
| 12 |
|
| 13 |
|
| 14 |
var nbRandoms = 100 |
| 15 |
|
| 16 |
|
| 17 |
type nbPoint Point |
| 18 |
|
| 19 |
func (p nbPoint) Compare(c Comparable, d Dim) float64 { q := c.(nbPoint); return p[d] - q[d] } |
| 20 |
func (p nbPoint) Dims() int { return len(p) } |
| 21 |
func (p nbPoint) Distance(c Comparable) float64 { |
| 22 |
q := c.(nbPoint) |
| 23 |
var sum float64 |
| 24 |
for dim, c := range p { |
| 25 |
d := c - q[dim] |
| 26 |
sum += d * d |
| 27 |
} |
| 28 |
return sum |
| 29 |
} |
| 30 |
|
| 31 |
|
| 32 |
type nbPoints []nbPoint |
| 33 |
|
| 34 |
func (p nbPoints) Index(i int) Comparable { return p[i] } |
| 35 |
func (p nbPoints) Len() int { return len(p) } |
| 36 |
func (p nbPoints) Pivot(d Dim) int { return nbPlane{nbPoints: p, Dim: d}.Pivot() } |
| 37 |
func (p nbPoints) Slice(start, end int) Interface { return p[start:end] } |
| 38 |
|
| 39 |
|
| 40 |
type nbPlane struct { |
| 41 |
Dim |
| 42 |
nbPoints |
| 43 |
} |
| 44 |
|
| 45 |
func (p nbPlane) Less(i, j int) bool { return p.nbPoints[i][p.Dim] < p.nbPoints[j][p.Dim] } |
| 46 |
func (p nbPlane) Pivot() int { return Partition(p, MedianOfRandoms(p, nbRandoms)) } |
| 47 |
func (p nbPlane) Slice(start, end int) SortSlicer { p.nbPoints = p.nbPoints[start:end]; return p } |
| 48 |
func (p nbPlane) Swap(i, j int) { |
| 49 |
p.nbPoints[i], p.nbPoints[j] = p.nbPoints[j], p.nbPoints[i] |
| 50 |
} |