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

时间:2015-12-18 00:40:03

标签: c++ arrays

我有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;
    }

3 个答案:

答案 0 :(得分:1)

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.

如果您需要使用许多,点,那么我建议对Nearest neighbor search algorithm进行一些研究,因为这可能会变慢。

答案 1 :(得分:0)

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

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*/
    }
}

答案 2 :(得分:0)

以下可能会有所帮助:

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);
}

Live Demo