Skip to content

Commit 6dda287

Browse files
author
Nadim-Mahmud
committed
jarvis algorithm added
1 parent 355e2d8 commit 6dda287

File tree

1 file changed

+95
-0
lines changed

1 file changed

+95
-0
lines changed
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
2+
3+
/// *** Jarvis Algorihtm [n*n]
4+
5+
6+
#define ll long long
7+
struct point{
8+
ll x,y;
9+
}convex_points[MX],points[MX];;
10+
11+
/// global scope decraltion of min-left point of collcetion
12+
point pivot;
13+
14+
///Distance calculation mathod
15+
ll dist(point p1,point p2){
16+
return ((p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y));
17+
}
18+
19+
double distd(point p1,point p2){
20+
return sqrt((p1.x-p2.x)*(p1.x-p2.x) + (p1.y-p2.y)*(p1.y-p2.y));
21+
}
22+
23+
/**
24+
* https://www.geeksforgeeks.org/orientation-3-ordered-points/
25+
* calculating orientation based on slope (yi-yj)/(xi-xj)
26+
* by compering slope of p-q and q-r;
27+
* if p-q<q-r then counter-clockwise
28+
* @return 0 if colinear
29+
* @return 1 if clockwise (Right rotetion)
30+
* @return 2 if counter-clockwise (left rotetion)
31+
*/
32+
int orientation(point p,point q,point r){
33+
ll val = ((q.y-p.y)*(r.x-q.x) - (r.y-q.y)*(q.x-p.x));
34+
if(val==0) return 0;
35+
if(val>0) return 1;
36+
return 2;
37+
}
38+
39+
/**
40+
* sorting by polor angle in counterclockwise order around point0.
41+
* If polor angle of two points is same, then put the nearest point first.
42+
*/
43+
bool cmp(point p1,point p2){
44+
ll o = orientation(pivot,p1,p2);
45+
if(o==0){
46+
return dist(pivot,p1) < dist(pivot,p2);
47+
}
48+
return (o==2);
49+
}
50+
51+
/// returning previous value of top element
52+
inline point nextToTop(stack<point>&st){
53+
point p,res;
54+
p = st.top();
55+
st.pop();
56+
res = st.top();
57+
st.push(p);
58+
return res;
59+
}
60+
61+
int total;
62+
63+
/**
64+
* This function will calculate convexHull points
65+
* All arrays are in 0 based indexing
66+
* @param n total numbers of points
67+
*/
68+
double convexHull(int n)
69+
{
70+
vector<point> hull;
71+
int l = 0;
72+
for (int i = 1; i < n; i++)
73+
if (points[i].x < points[l].x)
74+
l = i;
75+
int p = l, q;
76+
do
77+
{
78+
hull.push_back(points[p]);
79+
q = (p+1)%n;
80+
for (int i = 0; i < n; i++)
81+
{
82+
if (orientation(points[p], points[i], points[q]) == 2)
83+
q = i;
84+
}
85+
86+
p = q;
87+
88+
} while (p != l);
89+
double ans = distd(hull[0],hull[hull.size()-1]);
90+
for (int i = 0; i<hull.size()-1; i++){
91+
ans += distd(hull[i],hull[i+1]);
92+
//cout<<hull[i].x<<" "<<hull[i].y<<endl;
93+
}
94+
return ans;
95+
}

0 commit comments

Comments
 (0)