找到具有特定距离的第一个元素

时间:2013-04-21 09:05:38

标签: java recursion tree kdtree

我正在尝试编写一个方法,该方法将返回最接近3D空间中另一个点的点的索引。这些点存储在KD树中,我将它们与作为我方法参数的点p进行比较。这是方法:

public int NearestPointWithDistance(KDnnTreeNode node, Point p, Double distance){
  int index = -1;
  if(node == null){
     return -1;
  }else{
      double[] point_coordinates = data[node.eltIndex];
      Point q = new Point(point_coordinates[0],point_coordinates[1], point_coordinates[2]);
      if(KDnnTree.distance(p, q) == distance){
             return index;
      }  

      if(node.left != null){
          final int left_child = NearestPointWithDistance(node.left, p, distance);
      }
      if(node.right != null){
          final int right_child = NearestPointWithDistance(node.right, p, distance);
        }
    }
  return index;

}

问题是,可能存在多个具有相同距离的点。我得到的结果是一个点的索引列表(见下文),但我只想要列表的第一个元素(在下面的例子中,这将是数字54510)。

54510
54511
54512
54514
54518
54526
54543
54577
65355
76175
54482
54416
54278
21929
54001
74323 

我知道这不是搜索KD树中两个关闭点的方法,但我想首先尝试这种方式。

1 个答案:

答案 0 :(得分:0)

不要使用java.lang.Double作为参数。使用double

原因是如果您的KDNTree.distance()也会返回Double,您最终会比较对象的引用,而不是它们的值。

你有非常不方便的API。无论如何,做一个帮手功能:

public Point getNodePoint(Node node)
{
    double[] point_coordinates = data[node.eltIndex];
    return new Point(point_coordinates[0],point_coordinates[1], point_coordinates[2]);
}

使用最佳距离可用选项:

double result = KDnnTree.distance(p, q);
if (result == distance)
{
   return node.eltIndex;
}
index = node.eltIndex; // assume given node is best
if (node.left !=  null)
{
    final int left_child = NearestPointWithDistance(node.left, p, distance);
    double left_distance = KDnnTree.distance(p, getNodePoint(left_child);

    if (Math.abs(distance - result) > Math.abs(distance - left_distance))
    {
        // result given is closer to wanted point
        result = left_distance;
        index = left_child;
    }
}
if (node.right !=  null)
{
    final int right_child = NearestPointWithDistance(node.right, p, distance);
    double right_distance = KDnnTree.distance(p, getNodePoint(right_child);

    if (Math.abs(distance - result) > Math.abs(distance - right_distance))
    {
        // result given is closer to wanted point
        result = right_distance;
        index = right_child;
    }
}
return index;
相关问题