Skip to content

Instantly share code, notes, and snippets.

@withs
Created November 22, 2021 18:34
Show Gist options
  • Save withs/8f9fd3c3705753028af73391f9ec2ad7 to your computer and use it in GitHub Desktop.
Save withs/8f9fd3c3705753028af73391f9ec2ad7 to your computer and use it in GitHub Desktop.
Get the closest point to a desired coordinate in a 2D space
#include "iostream"
#include "vector"
#include <math.h>
struct Vec3 {
float x,y,z;
};
template <class T>
Vec3 getClosest(std::vector<T> withPosVec, const Vec3 toPos) noexcept {
float a;
float b;
// closest item of the vector above, we setup a base z wich (in our case is unused
// because we work on a 2D space then we uuse it to store the distance) is unreachable
Vec3 closest { 0, 0, (toPos.x + toPos.y) };
// iterate in the vector containing the positions
for ( Vec3& entry: withPosVec ) {
// Make sure we have absolute value
a = std::abs(entry.x - toPos.x);
b = std::abs(entry.y - toPos.y);
// basic Pythagorean calculation and checking if the result is lower of the current closest
if ( (entry.z = sqrt((a*a) + (b*b))) < closest.z )
closest = entry;
std::cout << "(" << entry.x << ", " << entry.y << ") = " << entry.z << '\n';
}
return closest;
}
int32_t main() {
// Vector of positions to test
std::vector<Vec3> positions = {
{ 1285.f, 810.f, 0.f },
{ 1283.f, 801.f, 0.f },
{ 1500.f, 808.f, 0.f },
{ 1300.f, 800.f, 0.f },
{ 1700.f, 400.f, 0.f },
{ 700.f, 1000.f, 0.f },
{ 200.f, 890.f, 0.f },
{ 2000.f, 1200.f, 0.f },
{ 239.f, 20.f, 0.f },
{ 20.f, 89.f, 0.f }
};
Vec3 closest = getClosest(positions, { 1280.f, 800.f, 0.f });
std::cout << "Closest is { " << closest.x << ", " << closest.y << ", " << closest.z << " }" << '\n';
}
/* Output:
(1285, 810) = 11.1803
(1283, 801) = 3.16228
(1500, 808) = 220.145
(1300, 800) = 20
(1700, 400) = 580
(700, 1000) = 613.514
(200, 890) = 1083.74
(2000, 1200) = 823.65
(239, 20) = 1300.8
(20, 89) = 1446.76
Closest is { 1283, 801, 3.16228 }
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment