Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.math.*;
- import java.util.*;
- // Gorozhankin Egor BS19-01
- public class A {
- public static void main(String[] args) {
- Scan scanner = new Scan(System.in);
- Segment segment1 = new Segment(scanner.nextLong(), scanner.nextLong(), scanner.nextLong(), scanner.nextLong());
- Segment segment2 = new Segment(scanner.nextLong(), scanner.nextLong(), scanner.nextLong(), scanner.nextLong());
- if (intersection(segment1, segment2)) {
- System.out.println("INTERSECTION");
- System.out.println(segment1);
- System.out.println(segment2);
- } else {
- System.out.println("NO INTERSECTIONS");
- }
- }
- static public boolean intersection(Segment a, Segment b) { // find intersection of two line segments
- double denominator = (a.begin.x - a.end.x) * (b.begin.y - b.end.y) - (a.begin.y - a.end.y) * (b.begin.x - b.end.x);
- if (denominator == 0)
- return false;
- double x = (a.begin.x * a.end.y - a.begin.y * a.end.x) * (b.begin.x - b.end.x) - (b.begin.x * b.end.y - b.begin.y * b.end.x) * (a.begin.x - a.end.x);
- double y = (a.begin.x * a.end.y - a.begin.y * a.end.x) * (b.begin.y - b.end.y) - (b.begin.x * b.end.y - b.begin.y * b.end.x) * (a.begin.y - a.end.y);
- if (a.checkCoordinate(x, y) && b.checkCoordinate(x, y))
- return true;
- return false;
- }
- }
- class Coordinate{
- public long x, y;
- public Coordinate(Long x, Long y) {
- this.x = x;
- this.y = y;
- }
- public boolean isEqual(double x, double y) { // check whether two coordinates are equal
- return x == this.x && y == this.y;
- }
- public String toString() { // prepare coordinate for output
- return Double.toString(x) + " " + Double.toString(y);
- }
- }
- class Segment{
- public Coordinate begin, end;
- public Segment(Long xBegin, Long yBegin, Long xEnd, Long yEnd){
- begin = new Coordinate(xBegin, yBegin);
- end = new Coordinate(xEnd, yEnd);
- }
- public boolean checkCoordinate(double x, double y) { // check whether point of intersection belongs to line segment
- boolean checkArea = ((x > begin.x && x < end.x) || (x < begin.x && x > end.x))
- && ((y > begin.y && y < end.y) || (y < begin.y && y > end.y))
- && ((x > begin.x && x < end.x) || (x < begin.x && x > end.x))
- && ((y > begin.y && y < end.y) || (y < begin.y && y > end.y));
- boolean checkEndPoints = begin.isEqual(x, y) || end.isEqual(x, y);
- return checkArea && !checkEndPoints;
- }
- public String toString() { // prepare segment for output
- return begin.toString() + " " + end.toString();
- }
- }
Add Comment
Please, Sign In to add comment