Search code examples
javaobjectmathmethods

Check If Two Rhombus Overlap In Java


I need to Check If Two Rhombus Overlap In Java, i dont understand how to do it properly

public class Rhombus {
    int p1;
    int p2;
    int p3;
    int p4;
    Rhombus(int p1, int p2, int p3, int p4){
        this.p1 = p1;
        this.p2 = p2;
        this.p3 = p3;
        this.p4 = p4;
    }
    void overlaps(Rhombus r){
        System.out.println("Checking if one rhombus intersects the second one:");
        if (r.p1 == this.p1 || r.p1 == this.p2 || r.p1 == this.p3 || r.p1 == this.p4 || r.p2 == this.p1 || r.p2 == this.p2 || r.p2 == this.p3 || r.p2 == this.p4 || r.p3 == this.p1 || r.p3 == this.p2 || r.p3 == this.p3 || r.p3 == this.p4 || r.p4 == this.p1 || r.p4 == this.p2 || r.p4 == this.p3 || r.p4 == this.p4 ) System.out.println("true");
        else System.out.println("false");
    }

    public static void main(String[] args) {
        Rhombus rhombus1 = new Rhombus(3, 3, 3, 3);
        Rhombus rhombus2 = new Rhombus(1, 5, 5, 5);
        rhombus1.overlaps(rhombus2);
    }
}

I try this, but it doesnt work if one point cross another rhombus


Solution

  • void overlaps(Rhombus r) {
            int x1 = Math.min(this.p1, Math.min(this.p2, Math.min(this.p3, this.p4)));
            int y1 = Math.min(this.p1, Math.min(this.p2, Math.min(this.p3, this.p4)));
            int x2 = Math.max(this.p1, Math.max(this.p2, Math.max(this.p3, this.p4)));
            int y2 = Math.max(this.p1, Math.max(this.p2, Math.max(this.p3, this.p4)));
            int x3 = Math.min(r.p1, Math.min(r.p2, Math.min(r.p3, r.p4)));
            int y3 = Math.min(r.p1, Math.min(r.p2, Math.min(r.p3, r.p4)));
            int x4 = Math.max(r.p1, Math.max(r.p2, Math.max(r.p3, r.p4)));
            int y4 = Math.max(r.p1, Math.max(r.p2, Math.max(r.p3, r.p4)));
    
            if (x1 < x4 && x2 > x3 && y1 < y4 && y2 > y3) {
                System.out.println("One rhombus intersects the other");
            } else {
                System.out.println("The two rhombuses do not intersect");
            }
        }