Skip to content

Commit 4017a1e

Browse files
Gorzoidleios
authored andcommitted
Added Jarvis March for C++ (#283)
* Added cpp file * Added Gorzoid to CONTRIBUTORS.md * Fixed style to conform with guidelines #18 * Removed unnecessary define * Added entry to jarvis_march.md * Added check for empty array edge case. Changed Iterators to single vector reference * Changed to resolve edge case of duplicate points.
1 parent 43437da commit 4017a1e

File tree

3 files changed

+77
-1
lines changed

3 files changed

+77
-1
lines changed

CONTRIBUTORS.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -48,8 +48,10 @@ Max Weinstein
4848
<br>
4949
Gibus Wearing Brony
5050
<br>
51+
Gorzoid
52+
<br>
5153
Arun Sahadeo
5254
<br>
5355
NIFR91
5456
<br>
55-
Michal Hanajik
57+
Michal Hanajik
Lines changed: 72 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,72 @@
1+
#include <vector>
2+
#include <iostream>
3+
#include <algorithm>
4+
5+
struct Point
6+
{
7+
double x, y;
8+
9+
bool operator==(const Point& b) const
10+
{
11+
return x == b.x && y == b.y;
12+
}
13+
14+
bool operator!=(const Point& b) const
15+
{
16+
return !(*this == b);
17+
}
18+
};
19+
20+
std::vector<Point> jarvis_march(const std::vector<Point>& points)
21+
{
22+
std::vector<Point> hull_points;
23+
24+
if(points.empty())
25+
return hull_points;
26+
27+
// Left most point
28+
auto first_point_it = std::min_element(points.begin(), points.end(), [](const Point& a, const Point& b){ return a.x < b.x; });
29+
30+
auto next_point_it = first_point_it;
31+
do
32+
{
33+
hull_points.push_back(*next_point_it);
34+
35+
const Point& p1 = hull_points.back();
36+
37+
// Largest internal angle
38+
next_point_it = std::max_element(
39+
points.begin(),
40+
points.end(),
41+
[p1](const Point& p2, const Point& p3){
42+
return (p1 == p2) || (p2.x - p1.x) * (p3.y - p1.y) > (p3.x - p1.x) * (p2.y - p1.y);
43+
}
44+
);
45+
}
46+
while(*next_point_it != *first_point_it);
47+
48+
return hull_points;
49+
}
50+
51+
int main() {
52+
std::vector<Point> points = {
53+
{ 1.0, 3.0 },
54+
{ 1.0, 3.0 },
55+
{ 2.0, 4.0 },
56+
{ 4.0, 0.0 },
57+
{ 1.0, 0.0 },
58+
{ 0.0, 2.0 },
59+
{ 2.0, 2.0 },
60+
{ 3.0, 4.0 },
61+
{ 3.0, 1.0 },
62+
};
63+
64+
auto hull_points = jarvis_march(points);
65+
66+
std::cout << "Hull points are:" << std::endl;
67+
68+
for(const Point& point : hull_points) {
69+
std::cout << '(' << point.x << ", " << point.y << ')' << std::endl;
70+
}
71+
}
72+

contents/jarvis_march/jarvis_march.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,8 @@ Program.cs
3838
[import, lang:"javascript"](code/javascript/jarvis-march.js)
3939
{% sample lang="py" %}
4040
[import, lang:"python"](code/python/jarvisMarch.py)
41+
{% sample lang="cpp" %}
42+
[import, lang:"c_cpp"](code/c++/jarvis_march.cpp)
4143
{% endmethod %}
4244

4345
<script>

0 commit comments

Comments
 (0)