diff --git a/CONTRIBUTORS.md b/CONTRIBUTORS.md index ff56551ba..6b3d1ec61 100644 --- a/CONTRIBUTORS.md +++ b/CONTRIBUTORS.md @@ -48,8 +48,10 @@ Max Weinstein
Gibus Wearing Brony
+Gorzoid +
Arun Sahadeo
NIFR91
-Michal Hanajik +Michal Hanajik \ No newline at end of file diff --git a/contents/jarvis_march/code/c++/jarvis_march.cpp b/contents/jarvis_march/code/c++/jarvis_march.cpp new file mode 100644 index 000000000..d2d420957 --- /dev/null +++ b/contents/jarvis_march/code/c++/jarvis_march.cpp @@ -0,0 +1,72 @@ +#include +#include +#include + +struct Point +{ + double x, y; + + bool operator==(const Point& b) const + { + return x == b.x && y == b.y; + } + + bool operator!=(const Point& b) const + { + return !(*this == b); + } +}; + +std::vector jarvis_march(const std::vector& points) +{ + std::vector hull_points; + + if(points.empty()) + return hull_points; + + // Left most point + auto first_point_it = std::min_element(points.begin(), points.end(), [](const Point& a, const Point& b){ return a.x < b.x; }); + + auto next_point_it = first_point_it; + do + { + hull_points.push_back(*next_point_it); + + const Point& p1 = hull_points.back(); + + // Largest internal angle + next_point_it = std::max_element( + points.begin(), + points.end(), + [p1](const Point& p2, const Point& p3){ + return (p1 == p2) || (p2.x - p1.x) * (p3.y - p1.y) > (p3.x - p1.x) * (p2.y - p1.y); + } + ); + } + while(*next_point_it != *first_point_it); + + return hull_points; +} + +int main() { + std::vector points = { + { 1.0, 3.0 }, + { 1.0, 3.0 }, + { 2.0, 4.0 }, + { 4.0, 0.0 }, + { 1.0, 0.0 }, + { 0.0, 2.0 }, + { 2.0, 2.0 }, + { 3.0, 4.0 }, + { 3.0, 1.0 }, + }; + + auto hull_points = jarvis_march(points); + + std::cout << "Hull points are:" << std::endl; + + for(const Point& point : hull_points) { + std::cout << '(' << point.x << ", " << point.y << ')' << std::endl; + } +} + diff --git a/contents/jarvis_march/jarvis_march.md b/contents/jarvis_march/jarvis_march.md index f9f9adee2..f30bd57e9 100644 --- a/contents/jarvis_march/jarvis_march.md +++ b/contents/jarvis_march/jarvis_march.md @@ -38,6 +38,8 @@ Program.cs [import, lang:"javascript"](code/javascript/jarvis-march.js) {% sample lang="py" %} [import, lang:"python"](code/python/jarvisMarch.py) +{% sample lang="cpp" %} +[import, lang:"c_cpp"](code/c++/jarvis_march.cpp) {% endmethod %}