Created
September 14, 2012 05:00
-
-
Save azmfaridee/3719894 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// this implementation has an error in the calculation, find the error | |
class Point { | |
public float x, y; | |
public Point(float x, float y) { | |
this.x = x; | |
this.y = y; | |
} | |
} | |
class Line { | |
public Point p1, p2; | |
private float a, b, c; | |
public Line(Point p1, Point p2) { | |
this.p1 = p1; | |
this.p2 = p2; | |
calculateCoEfficients(); | |
} | |
public Point getIntersectionPoint(Line l2) { | |
float x = 0; | |
float y = 0; | |
// TODO calcuate the intersection point of "this" line and line l2, | |
// then set the values to x and y | |
// we have two equations | |
// (a1)x + (b1)y + (c1) = 0 and | |
// (a2)x + (b2)y + (c2) = 0 | |
float a1 = this.a; | |
float b1 = this.b; | |
float c1 = this.c; | |
float a2 = l2.a; | |
float b2 = l2.b; | |
float c2 = l2.c; | |
// now we need to find the value of x and y | |
x = (c2 * b1 - c1 * b2) / (a1 * b2 - a2 * b1); | |
y = (a1 * c2 - a2 * c1) / (a2 * b1 - a1 * b2); | |
// END OF TODO SECTION | |
Point intersectionPoint = new Point(x, y); | |
return intersectionPoint; | |
} | |
public void calculateCoEfficients() { | |
// as we know, the euation is (x - x1)/(x1 - x2) = (y - y1)(y1 - y2) | |
float x1 = this.p1.x; | |
float x2 = this.p2.x; | |
float y1 = this.p1.x; | |
float y2 = this.p2.y; | |
// this we got by solving the eqn (x - x1)/(x1 - x2) = (y - y1)(y1 - y2) | |
a = (y1 - y2); | |
b = -(x1 - x2); | |
c = -x1 * (y1 - y2) + y1 * (x1 - x2); | |
} | |
} | |
public class LineIntersect { | |
public static void main(String[] args) { | |
Line l1 = new Line(new Point(-1, -1), new Point(5, 5)); | |
Line l2 = new Line(new Point(2, -2), new Point(-3, 3)); | |
Point intersectionPoint = l1.getIntersectionPoint(l2); | |
System.out.println("The lines intersect at " + intersectionPoint.x + " in x co-ordinate and " + intersectionPoint.y + " in y co-ordinate"); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment