从一组数字中找出最接近的三个数字值
Find nearest three values of a number from an array of numbers
我有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*/
}
}
相关文章:
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 在 2D 向量中使用第三个 [ ] 有什么意义?
- 如何通过按下第三个窗口中的按钮,将QString从一个窗口获取到另一个窗口
- 如何知道n!是否可以表示为三个连续数字的乘法?
- 使用三个数字比较器进行排序
- 有没有更简单的方法可以从用户那里获取三个数字并按升序打印它们?
- 数组中最大的三个数字
- 跳过每三个数字
- 三个数字之间的 C++ 相加两个更高的数字,没有循环和数组
- 如何使用不同的功能计算三个数字的总和,平均值和产物
- 创建一个程序,要求用户输入两个数字,并有三个可能的答案.代码未编译.数字(作为int)
- 为什么linear_congruenty_engine :: seed(sseq)丢弃了由种子序列生成的三个数字
- 根据列中的第三个数字对向量进行排序
- 三个数字彩票猜谜游戏C++
- 从一组数字中找出最接近的三个数字值
- 需要帮助获取数组中最小的三个数字
- 输入三个数字,并在c++中确定最高和最低的数字
- 三个不同的数字
- 为什么我在尝试输出UTF-8字符时会得到三个不同的数字
- 至少三个数字