从一组数字中找出最接近的三个数字值

Find nearest three values of a number from an array of numbers

本文关键字:数字 三个 最接近 一组      更新时间:2023-10-16

我有20个坐标x[20], y[20],我试图获得离用户坐标最近的3个坐标,这个函数应该返回3个最近值的索引。

    double distanceFormula(double x1, double x2, double y1, double y2){
        return sqrt(pow((x1 - x2), 2) + pow((y1 - y2), 2));
    }
    int* FindNearestThree(double keyX, double keyY, double x[], double y[]){
    int wanted [3];
    double distance;
    double distTemp;
    for (int i = 0; i<20; i++)
    {
        distTemp = formula(keyX, x[i], keyY, y[i]);
        if (distance != null || distance > distTemp){
            distance = distTemp;
            wanted[0] = i;
        }
        //this will get only the nearest value
    }
    return results;
    }
using Point = std::pair<int, int>;
std::array<Point, 20> points;
populate(points);
std::sort(
    points.begin()
  , points.end()
  , [up=get_user_coords()](const Point& p1, const Point& p2) {
        int d1 = std::pow(up.first - p1.first, 2) + std::pow(up.second - p1.second, 2);
        int d2 = std::pow(up.first - p2.first, 2) + std::pow(up.second - p2.second, 2);
        return d1 < d2;
    });
// The nearest 3 points are now at indices 0, 1, 2.

如果你需要处理更多的点,那么我建议对最近邻搜索算法进行一些研究,因为这可能会变得很慢很快。

以下可能会有所帮助:

template <std::size_t N, typename It, typename Queue>
std::array<It, N> asArray(Queue& queue, It emptyValue)
{
    std::array<It, N> res;
    for (auto& e : res) {
        if (queue.empty()) {
            e = emptyValue;
        } else {
            e = queue.top();
            queue.pop();
        }
    }
    return res;
}
template <std::size_t N, typename It, typename ValueGetter>
std::array<It, N>
MinNElementsBy(It begin, It end, ValueGetter valueGetter)
{
    auto myComp = [&](const It& lhs, const It& rhs)
    {
        return valueGetter(*lhs) <  valueGetter(*rhs);
    };
    std::priority_queue<It, std::vector<It>, decltype(myComp)> queue(myComp);
    for (auto it = begin; it != end; ++it) {
        queue.push(it);
        if (N < queue.size()) {
            queue.pop();
        }
    }
    return asArray<N>(queue, end);
}

实时演示

我想这可能是最简单、最丑陋的解决方案:

for (int j = 0; j <3; j++) {
  for (int i = 0; i<20; i++)
    { /* if statement needed here to check if you already 
      have current value in your result set
      and then your loop as it is*/
    }
}