Logo

Programming-Idioms

  • C++
  • Java
  • Dart
  • Clojure
  • Lua
  • Go
  • Python

Idiom #178 Check if point is inside rectangle

Set boolean b to true if if the point with coordinates (x,y) is inside the rectangle with coordinates (x1,y1,x2,y2) , or to false otherwise.
Describe if the edges are considered to be inside the rectangle.

b = (x1 < x < x2) and (y1 < y < y2)

Edges NOT considered to be inside.
class Rectangle:
    def __init__(self, x, y, w, h):
        self.x, self.y = x, y
        self.w, self.h = w, h
    def contains(self, x, y):
        a, b = self.x, self.y
        w, h = self.w, self.h
        return a <= x <= (a + w) and \
               b <= y <= (b + h)
w, h = x2 - x1, y2 - y1
r = Rectangle(x1, y1, w, h)
b = r.contains(x, y)
import java.awt.Rectangle;
int w = x2 - x1, h = y2 - y1;
Rectangle r = new Rectangle(x1, y1, w, h);
boolean b = r.contains(x, y);
import java.awt.geom.Rectangle2D;
double w = x2 - x1, h = y2 - y1;
Rectangle2D r = new Rectangle2D.Double(x1, y1, w, h);
boolean b = r.contains(x, y);
boolean b = x <= x2 && x >= x1 && y <= y2 && y >= y1;

Assume x1 <= x2 and y1 <= y2.
import "dart:math";
var r = Rectangle.fromPoints(Point(x1,y1),Point(x2,y2));
var b = r.containsPoint(Point(x,y));

Edges are considered to be inside the rectangle.
import "image"
p := image.Pt(x, y)
r := image.Rect(x1, y1, x2, y2)
b := p.In(r)

Points on the edge of the rectangle are considered as in the rectangle.
int isInsideRect(double x1, double y1, double x2, double y2, double px, double py){
	return px >= x1 && px <= x2 && py >= y1 && py <= y2; 
}

Using C convention with 1 for true and 0 for false.

Assuming that x1 < x2 and y1 < y2

New implementation...
< >
Bart