Sunday, January 9, 2011

Point in Triangle

The Problem

You are given the coordinates of the vertices of a triangle and also the coordinates of a point. You have to determine whether the point lies in the triangle or the it lies outside the triangle.

Logic Used

Distance of the point from a vertex is compared with the distances of the vertex from the other two vertices. If the distance of the point is found to be greater than any of the distances from other vertices, then the point lies outside the triangle. This is repeated for all the three vertices of the triangle.


#include<iostream>
#include<cmath>
using namespace std;
int main()
{
float dist(float,float,float,float);//Function to find the distance between two points.
float x1,x2,x3,y1,y2,y3,px,py,distance,length1,length2;
int out=0;
while(cin>>x1)
{
cin>>y1;
cin>>x2>>y2;
cin>>x3>>y3;
cin>>px>>py;
out=0;
length1=dist(x1,y1,x2,y2);
length2=dist(x1,y1,x3,y3);
distance=dist(x1,y1,px,py);
if(distance>length1 || distance>length2)
{
out=1;
}
length1=dist(x2,y2,x1,y1);
length2=dist(x2,y2,x3,y3);
distance=dist(x2,y2,px,py);
if(distance>length1 || distance>length2)
{
out=1;
}
length1=dist(x3,y3,x1,y1);
length2=dist(x3,y3,x2,y2);
distance=dist(x3,y3,px,py);
if(distance>length1 || distance>length2)
{
out=1;
}
if(out==0)
{cout<<"Inside"<<endl;}
else
{cout<<"Outside"<<endl;}
}
return 0;
}
float dist(float x1,float y1,float x2,float y2)
{
return sqrt(pow((x2-x1),2)+pow((y2-y1),2));
}

#include<iostream>


#include<cmath>


using namespace std;


int main()


{


float dist(float,float,float,float);//Function to find the distance between two points.


float x1,x2,x3,y1,y2,y3,px,py,distance,length1,length2;


int out=0;


while(cin>>x1)


{


cin>>y1;


cin>>x2>>y2;


cin>>x3>>y3;


cin>>px>>py;


out=0;


length1=dist(x1,y1,x2,y2);


length2=dist(x1,y1,x3,y3);


distance=dist(x1,y1,px,py);


if(distance>length1 || distance>length2)


{


out=1;


}


length1=dist(x2,y2,x1,y1);


length2=dist(x2,y2,x3,y3);


distance=dist(x2,y2,px,py);


if(distance>length1 || distance>length2)


{


out=1;


}


length1=dist(x3,y3,x1,y1);


length2=dist(x3,y3,x2,y2);


distance=dist(x3,y3,px,py);


if(distance>length1 || distance>length2)


{


out=1;


}


if(out==0)


{cout<<"Inside"<<endl;}


else


{cout<<"Outside"<<endl;}


}


return 0;


}


float dist(float x1,float y1,float x2,float y2)


{


return sqrt(pow((x2-x1),2)+pow((y2-y1),2));


}