Skip to content

Commit fb1fdf3

Browse files
Gathrosleios
authored andcommitted
Adding jarvis march in c (#91)
1 parent c35a0ea commit fb1fdf3

File tree

1 file changed

+70
-0
lines changed
  • chapters/computational_geometry/gift_wrapping/jarvis_march/code/c

1 file changed

+70
-0
lines changed
Lines changed: 70 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
#include <stdio.h>
2+
#include <stddef.h>
3+
#include <stdbool.h>
4+
5+
struct point {
6+
double x,y;
7+
};
8+
9+
struct point left_most_point(struct point *points, size_t num_points) {
10+
struct point ret = points[0];
11+
12+
for (size_t i = 0; i < num_points; ++i) {
13+
if (points[i].x < ret.x) {
14+
ret = points[i];
15+
} else if(points[i].x == ret.x) {
16+
if (points[i].y < ret.y) {
17+
ret = points[i];
18+
}
19+
}
20+
}
21+
22+
return ret;
23+
}
24+
25+
bool equal(struct point a, struct point b) {
26+
return a.x == b.x && a.y == b.y;
27+
}
28+
29+
double winding(struct point p, struct point q, struct point r) {
30+
return (q.x - p.x)*(r.y - p.y) - (q.y - p.y)*(r.x - p.x);
31+
}
32+
33+
size_t jarvis_march(struct point *points, struct point *hull_points,
34+
size_t num_points) {
35+
struct point hull_point = left_most_point(points, num_points);
36+
struct point end_point;
37+
38+
size_t i = 0;
39+
do {
40+
hull_points[i] = hull_point;
41+
end_point = points[0];
42+
43+
for (size_t j = 1; j < num_points; ++j) {
44+
if (equal(end_point, hull_point) ||
45+
winding(hull_points[i], end_point, points[j]) > 0.0) {
46+
end_point = points[j];
47+
}
48+
}
49+
50+
i++;
51+
hull_point = end_point;
52+
} while (!equal(end_point, hull_points[0]));
53+
54+
return i;
55+
}
56+
57+
int main() {
58+
struct point points[] = {{0.0, 0.0}, {-1.0, -1.0}, {1.0, 1.0}, {0.0, 1.0},
59+
{0.0, -1.0}, {2.0, 2.0}};
60+
struct point hull_points[6];
61+
62+
size_t num_hull_points = jarvis_march(points, hull_points, 6);
63+
64+
printf("The Hull points are:\n");
65+
for (size_t i = 0; i < num_hull_points; ++i) {
66+
printf("x=%f y=%f\n", hull_points[i].x, hull_points[i].y);
67+
}
68+
69+
return 0;
70+
}

0 commit comments

Comments
 (0)