After I published my first solution I got feedback that the same can be achieved calculating other way. So I tried implement another way:
Is it faster?
I did two tests:
1. I took solution 1 and 2 gave them the same data (line is not horizontal/vertical and point is not on the line) - solution 1 was 10-15% faster.
2. I add the same checking (the line is vertical/horizontal or point is on the line) to solution 1 and repeated test - both solution were performing almost identically.
public double distanceBetweenLineAndPoints(Point a, Point b, Point c){ double dx = a.x - b.x; double dy = a.y - b.y; if(dy == 0){ //we have vertical line return distanceBetweenPoints(new Point(c.x, a.y), c); } if(dx == 0){ //we have horizontal line return distanceBetweenPoints(new Point(a.x, c.y), c); } double slope = dy / dx; //lets check - may be c point is on the line if(c.y - a.y == slope * (c.x - a.x)){ //yes, it is return 0; } Point aa = new Point(); Point bb = new Point(); aa.x = c.x; aa.y = slope * (c.x - a.x)+ a.y; bb.x = (c.y - a.y)/slope + a.x; bb.y = c.y; return (distanceBetweenPoints(bb, c) / distanceBetweenPoints(aa, bb)) * distanceBetweenPoints(aa, c); }
Is it faster?
I did two tests:
1. I took solution 1 and 2 gave them the same data (line is not horizontal/vertical and point is not on the line) - solution 1 was 10-15% faster.
2. I add the same checking (the line is vertical/horizontal or point is on the line) to solution 1 and repeated test - both solution were performing almost identically.
No comments:
Post a Comment