Given four points of a rectangle, and one more point P. Write a function to check whether P lies within the given rectangle or not.
Input : R = [(10, 10), (10, -10), (-10, -10), (-10, 10)] P = (0, 0) Output : yes Illustration : Input : R = [(10, 10), (10, -10), (-10, -10), (-10, 10)], P = (20, 20) Output : no Illustration :
Approach : Let the coordinates of four corners be A(x1, y1), B(x2, y2), C(x3, y3) and D(x4, y4). And coordinates of the given point P be (x, y)
1) Calculate area of the given rectangle, i.e., area of the rectangle ABCD as area of triangle ABC + area of triangle ACD.
Area A = [ x1(y2 – y3) + x2(y3 – y1) + x3(y1-y2)]/2 + [ x1(y4 – y3) + x4(y3 – y1) + x3(y1-y4)]/2
2) Calculate area of the triangle PAB as A1.
3) Calculate area of the triangle PBC as A2.
4) Calculate area of the triangle PCD as A3.
5) Calculate area of the triangle PAD as A4.
6) If P lies inside the triangle, then A1 + A2 + A3 + A4 must be equal to A.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
This article is attributed to GeeksforGeeks.org