Created
September 25, 2018 02:35
-
-
Save Khalefa/d83447156acc9a60d8999e7d9d06ca5f to your computer and use it in GitHub Desktop.
C++ hw1 solution
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <math.h> | |
#include <vector> | |
#include <iostream> | |
using namespace std; | |
struct point { | |
float x, y; | |
point(float xx, float yy) :x{ xx }, y{ yy } {} | |
}; | |
ostream& operator <<(ostream &os, const point &p) { | |
os << "("; | |
os << p.x << "," << p.y << ")"; | |
return os; | |
} | |
struct Distance { | |
float virtual operator() (point a, point b) = 0; | |
}; | |
struct Euclidean :Distance { | |
float operator() (point a, point b) { | |
float dist = (a.x - b.x)*(a.x - b.x) + (a.y - b.y)*(a.y - b.y); | |
return sqrt(dist); | |
} | |
}; | |
struct Manhattan :Distance { | |
float operator() (point a, point b) { | |
float dist = abs(a.x - b.x) + abs(a.y - b.y); | |
return dist; | |
} | |
}; | |
point closest(vector<point> &pnts, point q, Distance& d) { | |
point p = pnts[0]; | |
float dist = d(p, q); | |
float min_dist = dist; | |
for (int i = 1; i < pnts.size(); i++) { | |
dist = d(pnts[i], q); | |
if (dist < min_dist) { | |
min_dist = dist; | |
p = pnts[i]; | |
} | |
} | |
return p; | |
} | |
template <typename D> | |
point closest(vector<point> &pnts, point q) { | |
point p = pnts[0]; | |
float dist = D()(p, q); | |
float min_dist = dist; | |
for (int i = 1; i < pnts.size(); i++) { | |
dist = D()(pnts[i], q); | |
if (dist < min_dist) { | |
min_dist = dist; | |
p = pnts[i]; | |
} | |
} | |
return p; | |
} | |
int main() { | |
vector<point> pnts{ point(10,20), point(1,1), point(2,2), point(3,3) }; | |
cout << closest(pnts, point(4, 4), Euclidean()); | |
cout << closest<Euclidean>(pnts, point(4, 4)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment