java - Constructing a 3D KD Tree -
so trying construct 3d kd tree list of randomly generated points. trying accomplish task recursively well. in recursion facing error when i'm trying partition list of points. code follows:
public class scratch { /** * @param args command line arguments */ public static void main(string[] args) { arraylist<point> points = new arraylist<point>(); random rand = new random(system.currenttimemillis()); (int = 0; < 100; i++) { double x = rand.nextint(100); double y = rand.nextint(100); double z = rand.nextint(100); point point = new point(x, y, z); points.add(point); } node root = kdtree(points, 0); system.out.println("done"); } static class node { node leftchild; node rightchild; point location; node() { } node(node leftchild, node rightchild, point location) { this.leftchild = leftchild; this.rightchild = rightchild; this.location = location; } } public static node kdtree(arraylist<point> points, int depth) { int axis = depth % 3; switch (axis) { case 0: collections.sort(points, point.x_comparator); break; case 1: collections.sort(points, point.y_comparator); break; case 2: collections.sort(points, point.z_comparator); break; default: break; } int middle = points.size() / 2; point median = points.get(middle); arraylist<point> greater = new arraylist<point>(points.sublist(0, (middle - 1))); arraylist<point> lesser = new arraylist<point>(points.sublist((middle + 1), (points.size()))); node node = new node(); node.location = median; if(greater.size() == 0 || lesser.size() == 0) { node.leftchild = null; node.rightchild = null; } else { node.leftchild = kdtree(lesser, depth + 1); node.rightchild = kdtree(greater, depth + 1); } return node; } }
the class point simple object contains x, y , z coordinate. , 3 comparators used based on depth of tree. error getting follows:
exception in thread "main" java.lang.illegalargumentexception: fromindex(0) > toindex(-1) @ java.util.arraylist.sublistrangecheck(arraylist.java:1006) @ java.util.arraylist.sublist(arraylist.java:996) @ scratch.scratch.kdtree(scratch.java:71) @ scratch.scratch.kdtree(scratch.java:80) @ scratch.scratch.kdtree(scratch.java:79) @ scratch.scratch.kdtree(scratch.java:79) @ scratch.scratch.kdtree(scratch.java:79) @ scratch.scratch.kdtree(scratch.java:79) @ scratch.scratch.main(scratch.java:32)
im gonna go on guess here , if have 1 point (or 0) on points array, when middle=points.size/2 equals 0 (integer division) , when try make sublist 0 -1 throws exception.
Comments
Post a Comment