Logo

Programming-Idioms

  • JS
  • Ruby
  • 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.

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)
b = (x1 < x < x2) and (y1 < y < y2)

Edges NOT considered to be inside.
const pointInRect = ({x1, y1, x2, y2}, {x, y}) => (
  (x > x1 && x < x2) && (y > y1 && y < y2)
)
Point = Struct.new(:x, :y)

Rect  = Struct.new(:x1, :y1, :x2, :y2) do
  def contains?(point)
    point.x.between?(x1,x2) && point.y.between?(y1,y2)
  end
end

b = Rect.new(0,0,2,5).contains?(Point.new(0,0))

Ruby has no predefined Rect or Point classes. Edges are considered to be inside.
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