Skip to content

Instantly share code, notes, and snippets.

@abel-masila
Created March 1, 2023 20:18
Show Gist options
  • Save abel-masila/83c38732bd0d63f6c55437f50eb92f09 to your computer and use it in GitHub Desktop.
Save abel-masila/83c38732bd0d63f6c55437f50eb92f09 to your computer and use it in GitHub Desktop.
function belongsToTriangle(x1, y1, x2, y2, x3, y3, xp, yp, xq, yq) {
// Calculate the length of the sides of the triangle
const lab = Math.sqrt((x2 - x1) ** 2 + (y2 - y1) ** 2);
const lac = Math.sqrt((x3 - x1) ** 2 + (y3 - y1) ** 2);
const lbc = Math.sqrt((x3 - x2) ** 2 + (y3 - y2) ** 2);
// Check if the triangle is non-degenerate
if (lab + lac <= lbc || lab + lbc <= lac || lac + lbc <= lab) {
return "o";
}
// Calculate the area of the triangle using Heron's formula
const s = (lab + lac + lbc) / 2;
const area = Math.sqrt(s * (s - lab) * (s - lac) * (s - lbc));
// Calculate the areas of the three sub-triangles formed by the point p
const area1 = Math.abs((x1 * (y2 - yp) + x2 * (yp - y1) + xp * (y1 - y2)) / 2);
const area2 = Math.abs((x2 * (y3 - yp) + x3 * (yp - y2) + xp * (y2 - y3)) / 2);
const area3 = Math.abs((x3 * (y1 - yp) + x1 * (yp - y3) + xp * (y3 - y1)) / 2);
// Check if point p is inside the triangle
if (Math.abs(area - (area1 + area2 + area3)) <= Number.EPSILON) {
// Point p belongs to the triangle
if (xq >= Math.min(x1, x2, x3) && xq <= Math.max(x1, x2, x3) && yq >= Math.min(y1, y2, y3) && yq <= Math.max(y1, y2, y3)) {
// Point q also belongs to the triangle
return "a";
} else {
// Point q does not belong to the triangle
return "1";
}
} else {
// Point p does not belong to the triangle
if (xq >= Math.min(x1, x2, x3) && xq <= Math.max(x1, x2, x3) && yq >= Math.min(y1, y2, y3) && yq <= Math.max(y1, y2, y3)) {
// Point q belongs to the triangle
return "2";
} else {
// Neither point p nor point q belongs to the triangle
return "o";
}
}
}
// Example usage
console.log(belongsToTriangle(0, 0,
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment