How to determine whether two axis‑aligned rectangles overlap in Ruby

1 Answer

0 votes
#
# Axis‑aligned rectangles are simply rectangles whose edges are parallel to the 
# coordinate axes — meaning their sides are horizontal and vertical. 
# That single assumption makes the overlap test dramatically simpler and faster.
#

#
#    Rectangle overlap detection (axis-aligned)
#
#    Each rectangle is defined by:
#        - x, y : coordinates of its top-left corner
#        - w, h : width and height
#
#    Two rectangles DO NOT overlap if any separating condition is true:
#        - One is completely to the left of the other
#        - One is completely to the right of the other
#        - One is completely above the other
#        - One is completely below the other
#
#    Otherwise, they overlap.
#
#    This is the standard O(1) test for axis-aligned rectangles.
#

class Rect
  attr_accessor :x, :y, :w, :h   # top-left X, top-left Y, width, height

  def initialize(x, y, w, h)
    @x = x
    @y = y
    @w = w
    @h = h
  end
end

#
#    Returns true if rectangles A and B overlap.
#
def rectangles_overlap(a, b)
  # Compute edges of A
  a_left   = a.x
  a_right  = a.x + a.w
  a_top    = a.y
  a_bottom = a.y + a.h

  # Compute edges of B
  b_left   = b.x
  b_right  = b.x + b.w
  b_top    = b.y
  b_bottom = b.y + b.h

  # Separating conditions:
  return false if a_right <= b_left   # A is left of B
  return false if b_right <= a_left   # B is left of A
  return false if a_bottom <= b_top   # A is above B
  return false if b_bottom <= a_top   # B is above A

  true  # Otherwise, they overlap
end

# Example rectangles
a = Rect.new(10, 10, 30, 20)   # Example rectangle A
b = Rect.new(25, 15, 40, 25)   # Overlaps A
c = Rect.new(100, 100, 10, 10) # Does not overlap A

puts "A vs B overlap? #{rectangles_overlap(a, b) ? 'YES' : 'NO'}"
puts "A vs C overlap? #{rectangles_overlap(a, c) ? 'YES' : 'NO'}"


#
# run:
#
# A vs B overlap? YES
# A vs C overlap? NO
#

 



answered Jul 18 by avibootz

Related questions

...