Skip to content

Instantly share code, notes, and snippets.

@yoxisem544
Created April 30, 2015 04:15
Show Gist options
  • Save yoxisem544/114300c9307660a5a7d6 to your computer and use it in GitHub Desktop.
Save yoxisem544/114300c9307660a5a7d6 to your computer and use it in GitHub Desktop.
import java.util.Scanner;
import java.io.*;
public class HW2 {
public static void main(String[] args) throws IOException {
BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));
String list1 = bf.readLine();
String[] l1 = list1.split(" ");
double[] li1 = new double[l1.length];
for (int i = 0; i < l1.length; i++) {
li1[i] = Double.valueOf(l1[i]);
}
double x1 = li1[0];
double y1 = li1[1];
double x2 = li1[2];
double y2 = li1[3];
double x3 = li1[4];
double y3 = li1[5];
double x4 = li1[6];
double y4 = li1[7];
isIntersect(x1,y1,x2,y2,x3,y3,x4,y4);
}
public static double getSlope(double x1, double y1, double x2, double y2) {
return (y2 - y1) / (x2 - x1);
}
public static void isIntersect(double x1, double y1, double x2, double y2, double x3, double y3, double x4, double y4) {
double m1 = getSlope(x1,y1,x2,y2);
double m2 = getSlope(x3,y3,x4,y4);
double x1_const = -(m1 * x1) + y1;
double x2_const = -(m2 * x3) + y3;
double x = (x2_const - x1_const) / (m1 - m2);
double y = m1 * (x - x1) + y1;
if (m1 == Double.POSITIVE_INFINITY || m1 == Double.NEGATIVE_INFINITY) {
x = x1;
y = m2 * (x - x3) + y3;
} else if (m2 == Double.POSITIVE_INFINITY || m2 == Double.NEGATIVE_INFINITY) {
x = x3;
y = m1 * (x - x1) + y1;
}
if (!Double.isNaN(x) || !Double.isNaN(y)) {
if (x > x1 && x > x2 || x < x1 && x < x2) {
System.out.println("No intersect");
} else if (y > y1 && y > y2 || y < y1 && y < y2) {
System.out.println("No intersect");
} else if (x > x3 && x > x4 || x < x3 && x < x4) {
System.out.println("No intersect");
} else if (y > y3 && y > y4 || y < y3 && y < y4) {
System.out.println("No intersect");
} else {
System.out.println("Intersect at (" + x + ", " + y + ").");
}
} else {
System.out.println("Two line parallel.");
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment