Kerflyn's Blog

Well… It's a blog!

“Is this point inside this rectangle?” without IF

leave a comment »

The class Point is given below. The hasCode() method uses an helper that you can find in guava. The method equals() contains the only if in this post (promised ;)).

public class Point {
    public final int x;
    public final int y;

    public Point(int x, int y) {
        this.x = x;
        this.y = y;
    }

    @Override
    public int hashCode() {
        return Objects.hashCode(x, y);
    }

    @Override
    public boolean equals(Object obj) {
        if (obj == null || !(obj instanceof Point)) {
            return false;
        }
        Point point = (Point) obj;
        return x == point.x && y == point.y;
    }
}

Here is the class Rectangle:

public class Rectangle {
    public final Point start;
    public final Point end;

    public Rectangle(Point start, Point end) {
        this.start = start;
        this.end = end;
    }
}

I suppose that start.x < end.x and that start.y < end.y

I define the minimum and the maximum of two points as the point which coordinates are respectively the minimum and the maximum of the coordinates of the given points. For example, the minimum of the points (1, 4) and (3, 2) is (1, 2), and the maximum is (3, 4).

public class Points {
    // it's an utility class
    private Points() { throw new UnsupportedOperationException(); }

    public static Point min(Point p1, Point p2) {
        return new Point(Math.min(p1.x, p2.x), Math.min(p1.y, p2.y));
    }

    public static Point max(Point p1, Point p2) {
        return new Point(Math.max(p1.x, p2.x), Math.max(p1.y, p2.y));
    }
}

Now, I give the method Rectangle.contains() that checks if a point is inside a rectangle. The idea is to use the methods min() and max() between the given point and the rectangle edges as filters: if the computed point is different from the given point, then the given point is not in the rectangle.

import static Points.*;

public class Rectangle {
    // see code above...

    public boolean contains(Point point) {
        return point.equals(max(start, min(end, point)));
    }
}

Written by fsarradin

2011/05/04 at 07:01

Posted in Programming

Tagged with ,

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: