0x45
0x45

Reputation: 819

Compute intersection of two identical objects

I've got 2 Rectangles, both have the same edges.

new Rectangle(Arrays.asList(new Coord(1,1), new Coord(2,1), new Coord(2,2), new Coord(1,2)));

From my understanding the Intersection should be 1, however my function returns -1.

public Rectangle(List<Coord> edges){
        Assert.assertTrue("Provide an exact number of 4 edges", edges.size() == 4);
        this.edges = edges;
        left = getLeft(edges);
        right = getRight(edges);
        top = getTop(edges);
        bottom = getBottom(edges);
    }

private static int computeIntersection(Rectangle rect1, Rectangle rect2){

        int x_overlap = Math.min(rect1.right, rect2.right) - Math.max(rect1.left, rect2.left);
        int y_overlap = Math.min(rect1.bottom,rect2.bottom) - Math.max(rect1.top,rect2.top);
        System.out.println(x_overlap * y_overlap);


        return x_overlap * y_overlap;

    }

Do I have a problem with my math there, when computing the intersection or what did I not consider?

Upvotes: 0

Views: 64

Answers (1)

xingbin
xingbin

Reputation: 28289

First, you should check if the two rectangle is actually overlapped or not.

And, you should use the min top substract the max bottom.

private static int computeIntersection(Rectangle rect1, Rectangle rect2){
    if (rect1.left >= rect2.right || rect2.left >= rect1.right
            || rect1.bottom >= rect2.top || rect2.bottom >= rect1.top) {
        return 0;
    } else {
        int x_overlap = Math.min(rect1.right, rect2.right) - Math.max(rect1.left, rect2.left);
        int y_overlap = Math.min(rect1.top,rect2.top) - Math.max(rect1.bottom,rect2.bottom);
        return x_overlap * y_overlap;
    }
}

Upvotes: 1

Related Questions