Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Broken KdNode equals and compareTo causes the KdTree not to return all valid results #159

Open
wants to merge 2 commits into
base: master
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
3 changes: 2 additions & 1 deletion src/com/jwetherell/algorithms/data_structures/KdTree.java
Original file line number Diff line number Diff line change
Expand Up @@ -588,7 +588,8 @@ public boolean equals(Object obj) {
*/
@Override
public int compareTo(KdNode o) {
return compareTo(depth, k, this.id, o.id);
int depthCompare = Integer.compare(this.depth, o.depth);
return depthCompare != 0 ? depthCompare : this.id.compareTo(o.id);
}

/**
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package com.jwetherell.algorithms.data_structures.test;

import static org.junit.Assert.assertTrue;
import static org.junit.Assert.assertEquals;

import java.util.ArrayList;
import java.util.Collection;
Expand Down Expand Up @@ -36,9 +37,9 @@ public void testKdTree() {
XYZPoint search = new XYZPoint(1, 4);
result = kdTree.nearestNeighbourSearch(4, search);
assertTrue("K-D Tree query error. query=(k=4, p=(1, 4)) returned="+result, (result.contains(p1) &&
result.contains(p2) &&
result.contains(p4) &&
result.contains(p6))
result.contains(p2) &&
result.contains(p4) &&
result.contains(p6))
);

kdTree.remove(p6);
Expand Down Expand Up @@ -67,6 +68,21 @@ public void testKdTree_as_iterable() {
KdTree<XYZPoint> kdTree = new KdTree<XYZPoint>(points);

for (final XYZPoint p : kdTree)
assertTrue(kdTree.contains(p));
assertTrue(kdTree.contains(p));
}

@Test
public void testKdTreeNearestNeighbour() {
List<XYZPoint> points = new ArrayList<XYZPoint>();
XYZPoint p1 = new XYZPoint(0, 0, 0);
points.add(p1);
XYZPoint p2 = new XYZPoint(-1, 0, 1);
points.add(p2);
XYZPoint p3 = new XYZPoint(2, 0, -2);
points.add(p3);
KdTree<XYZPoint> kdTree = new KdTree<XYZPoint>(points);

Collection<XYZPoint> result = kdTree.nearestNeighbourSearch(3, p1);
assertEquals("K-D Tree query error. expected all points to be returned" + result, 3, result.size());
}
}