Skip to content

Added Jarvis March for C++ #283

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 8 commits into from
Aug 3, 2018
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 3 additions & 1 deletion CONTRIBUTORS.md
Original file line number Diff line number Diff line change
Expand Up @@ -48,8 +48,10 @@ Max Weinstein
<br>
Gibus Wearing Brony
<br>
Gorzoid
<br>
Arun Sahadeo
<br>
NIFR91
<br>
Michal Hanajik
Michal Hanajik
72 changes: 72 additions & 0 deletions contents/jarvis_march/code/c++/jarvis_march.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,72 @@
#include <vector>
#include <iostream>
#include <algorithm>

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<Point> jarvis_march(const std::vector<Point>& points)
{
std::vector<Point> 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<Point> 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;
}
}

2 changes: 2 additions & 0 deletions contents/jarvis_march/jarvis_march.md
Original file line number Diff line number Diff line change
Expand Up @@ -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 %}

<script>
Expand Down