読者です 読者をやめる 読者になる 読者になる

argius note

プログラミング関連

開発しています



長方形の交差判定 (2)

Ruby

復習がてら、Ruby版。

class Rectangle
  attr_reader :left, :top, :right, :bottom
  def initialize(left, top, right, bottom)
    @left, @top, @right, @bottom = left, top, right, bottom
  end
  def valid?
    left < right and top < bottom
  end
end

def overlap? (r1, r2)
  Rectangle.new([r1.left, r2.left].max,
                [r1.right, r2.right].min,
                [r1.top, r2.top].max,
                [r1.bottom, r2.bottom].min).valid?
end

def checkOverlap (r1, r2)
  if !r1.valid? or !r2.valid?
    puts "r1 or r2 is not valid"
  else
    puts overlap?(r1, r2) ? "overlapped" : "not overlapped"
  end
end

checkOverlap(Rectangle.new(0, 10, 10, 100), Rectangle.new(0, 10, 10, 100))
checkOverlap(Rectangle.new(0, 10, 10, 101), Rectangle.new(0, 10, 10, 100))
checkOverlap(Rectangle.new(10, 10, 150, 150), Rectangle.new(175, 15, 180, 130))
$ ./check.rb
overlapped
overlapped
not overlapped
$