Hei, I got Challenge to my email and I thought - why not :)
Distance:
In 2D coordinate system we have three points A(x,y) B(x,y) C(x,y) where x,y can be positive and negative integer numbers If Points A and B define endless line, write function which returns the
distance between point C and the line defined by point A, B
I havn't thought it will be so easy:
public class DistanceCalculator {
public static double distanceBetweenPoints(Point p1, Point p2){
int dx = p1.x - p2.x;
int dy = p1.y - p2.y;
return Math.sqrt(dx*dx + dy*dy);
}
public static double distanceBetweenLineAndPoints(Point a, Point b, Point c){
//lets find area of triangle
double ab = distanceBetweenPoints(a, b);
double bc = distanceBetweenPoints(b, c);
double ca = distanceBetweenPoints(c, a);
double p = (ab + bc + ca)/2;
double area = Math.sqrt(p*(p-ab)*(p-bc)*(p-ca));
return (area*2)/ab;
}
}
public class Point {
public int x;
public int y;
public Point (int x, int y){
this.x = x;
this.y = y;
}
}
If you like it - there is also Part2.
No comments:
Post a Comment