Skip to content

Instantly share code, notes, and snippets.

@Stephenitis
Last active December 19, 2015 13:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Stephenitis/5962740 to your computer and use it in GitHub Desktop.
Save Stephenitis/5962740 to your computer and use it in GitHub Desktop.
find a point within a triangle
#Stephen Nguyen - July 10
# drew a point within a triangle and realized that the point within the
# triangle makes 3 smaller triangles whose area is equal to the area of the triangle
# if outside the triangle the area will always be greater than the the area of the triangle
# method will calculate the area of three points by inputting the length of the 3 triangle sides into heron's formula
# heron's formula was looked up to complete this http://matrixpp.blogspot.com/2012/11/herons-formula.html
def area(point_1, point_2, point_3)
side_1 = Math.hypot(point_2[0]-point_1[0], point_2[1]-point_1[1])
side_2 = Math.hypot(point_3[0]-point_1[0], point_3[1]-point_1[1])
side_3 = Math.hypot(point_3[0]-point_2[0], point_3[1]-point_2[1])
s = ((side_1 + side_2 + side_3)/2)
area = Math.sqrt(s*(s-side_1)*(s-side_2)*(s-side_3))
end
def inside_triangle?(point_1, point_2, point_3, point_x)
area_1 = area(point_x, point_1, point_2)
area_2 = area(point_x, point_2, point_3)
area_3 = area(point_x, point_1, point_3)
#if true then point is inside the triangle
(area_1 + area_2 + area_3) == area(point_1, point_2, point_3)
end
#inside
inside_triangle?([0,0],[0,5],[5,0],[1,1]) == true
#on vertex
inside_triangle?([0,0],[0,5],[5,0],[0,0]) == true
#way outside positive
inside_triangle?([0,0],[0,5],[5,0],[99,99]) == false
#way outside negative
inside_triangle?([0,0],[0,5],[5,0],[-99,-99]) == false
# improvements 3-4 arguments per method is too many
# could be more readable & object oriented if triangle and points were their own classes
#this was a terrible path to go down. I have corrected my solution below.
#if output of three checks is equal for checks then point 4 is within the triangle
#if output is different for three checks then point 4 is outside of the triangle
def inside_triangle?(point1, point2, point3, point4)
if check(point1, point2, point4) == check(point1, point3, point4) &&
check(point2, point3, point4) == check(point1, point3, point4) &&
check(point1, point2, point4) == check(point2, point3, point4)
return true
else
false
end
end
def check(pointa, pointb, point4)
((point4[0] - pointa[0]) * (pointb[1] - pointa[1])) - ((pointb[0] - pointa[0]) * (point4[1]- pointa[1]))
end
point1 = [1,1]
point2 = [1,5]
point3 = [5,1]
point4 = [99,99]
inside_triangle?(point1, point2, point3, point4) == false
point4 = [1,1]
inside_triangle?(point1, point2, point3, point4) == true
#broken
point4 = [1,2]
inside_triangle?(point1, point2, point3, point4) == true
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment