【问题标题】:Finding the first element with a specific distance查找具有特定距离的第一个元素
【发布时间】:2013-04-14 07:39:39
【问题描述】:

我正在尝试编写一个方法,该方法将返回最接近 3D 空间中另一个点的点的索引。这些点存储在 KD 树中,我将它们与点 p 进行比较,点 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 树中搜索两个闭合点的方法,但我想先尝试这种方法。

【问题讨论】:

  • 你需要从左右比较结果,只取一个。

标签: java recursion tree kdtree


【解决方案1】:

不要使用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;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-11-19
    • 2013-11-10
    • 1970-01-01
    • 2017-04-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-07-14
    相关资源
    最近更新 更多