【问题标题】:Performance issue with a n X n search in a container在容器中进行 n X n 搜索的性能问题
【发布时间】:2021-12-16 22:23:49
【问题描述】:

我有一个几何(顶点)的自定义数组实现。数组的每个元素都由具有 Point 的顶点表示。现在我想检查数组中顶点的每个点之间的距离。因此,基本上对于大小为 n 的数组中的每个顶点,我将循环直到 n 并计算顶点与数组中所有 n 个顶点的距离。所以一个伪代码会是这样的

    func MyFunc( Array iVrtxList , vrtx inpVertex )
     {
        point refPt = inpVertex->getPoint(); 
       for ( i=0 ; i < iVrtxList.size(); i++)   
       {
            if( distanceBetween(iVertexList(i).point ,rePt ) == 0 )
               return 
       }
       iVrtxList.add(inpVertex);
      }
}

所以我想避免 N X N 循环。我想对容器进行排序,然后只检查距离的后续元素。但是我似乎错过了一些元素

【问题讨论】:

  • 我认为您正在尝试做的是单源最短路径问题的一个实例。您可以在以下位置了解问题及其时间复杂度:en.wikipedia.org/wiki/Shortest_path_problem
  • @gst 类似于具有顶点的图。但我想知道他们每个人之间的距离。我有一条边,它有 n 个顶点。有时你可能最终有重复的顶点,所以为了过滤它们,我们检查它们之间的距离是否为 0
  • 您似乎只是在检查以确保您没有两次添加相同的点。一种更快的方法是将点保留在 Set/Map/Hashset/Dictionary 中,然后检查该点是否已经在 Hashmap 中(或者在您使用的编程语言中调用的任何内容)。
  • 我确信这可能是一个经典的几何情况。您有一条线边,并且有您要检查的边的顶点。所以有一个 start vertex 和一个 end vertex 。因此,如果有 100 个顶点,我应该有 50 个唯一顶点,因为剩余的 50 个将作为后续点的 startVertex == endVertex 重复
  • 我看到了这个 R 实现 stackoverflow.com/questions/40999545/… 但我想要它的算法实现

标签: algorithm loops sorting geometry


【解决方案1】:

我有点实现了我们的目标,即在不使用 N X N 方法的情况下跳过重复的顶点。我使用多图来跟踪顶点。密钥使用 x,y,z 值进行哈希处理,我们将其调整为精度以使其与数据集一起使用。然而,哈希计算是脆弱的,因为任何导致冲突的映射都会破坏目的。以下是定义

class PointCoords
{
public:

    PointCoords(double  ix, double iy, double iz) : _x(ix), _y(iy), _z(iz) { };

    double _x;
    double _y;
    double _z;

};

class PointCoords_hash
{
public:
    size_t operator()(const PointCoords& v) const
    {
        auto f1 = std::hash<double>{}(round(v._x * 10) / 10);
        auto f2 = std::hash<double>{}(round(v._y * 10) / 10);
        auto f3 = std::hash<double>{}(round(v._z * 10) / 10);
        size_t hCode = (f1 ^ f2 ^ f3) << 1;
        return ((f1 ^ f2 ^ f3) << 1);
    };
};

class PointCoords_equal
{
public:
    bool operator()(const PointCoords& u, const PointCoords& v) const
    {
        return (equal(u._x, v._x, 1e-6) &&
            equal(u._y, v._y, 1e-6) &&
            equal(u._z, v._z, 1e-6));
    };
};
bool :equal( double d1, double d2, double err) 
{
    
    return ( fabs( d1 -d2) <= err);
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-09-16
    • 2022-12-22
    • 1970-01-01
    • 1970-01-01
    • 2015-12-24
    • 1970-01-01
    • 2014-08-06
    • 1970-01-01
    相关资源
    最近更新 更多