エロと風俗情報満載 どう抜く? へ投稿 その3

また投稿。しつこい。


お題は「長方形の交差判定」。出題文は以下。

ここに二つの長方形があります。左上隅のx座標、y座標、右下隅のx座標、y座標をそれぞれleft, top, right, bottomとします。また、おのおのの長方形についてleft < right, top < bottom が成り立つものとします。

この二つの長方形が重なっているかどうかを判定するコードを書いてください。なお辺で接する場合(例えば(0, 0, 100, 100)と(100, 0, 200, 100))は重なっていないものとします。

なお変数名に関して、例えば1番目の長方形の左上隅x座標がleft[0]なのかleft1なのか、それともrect1.leftなのかは自由に選んで構いません。

で、回答したコードがこれ。

Rectangle: class {
  + _top; + _right; + _bottom; + _left;

  initialize: method(top: 0, right: 0, bottom: 0, left: 0) {
    _top = top;
    _right = right;
    _bottom = bottom;
    _left = left;
  }

  is_overlapped: method(other) {
    return (math::min(_right, other.right) - math::max(_top, other.left) > 0 &&
            math::min(_bottom, other.bottom) - math::max(_left, other.top) > 0);
  }

  to_s: method() {
    return [_top, _right, _bottom, _left].to_s;
  }
}

r1: Rectangle(top: 10, right: 20, bottom: 20, left: 10);
[ // overlapped
  Rectangle(top: 10, right: 20, bottom: 20, left: 10), // 一致
  Rectangle(top: 11, right: 19, bottom: 19, left: 11), // 内
  Rectangle(top: 9, right: 21, bottom: 21, left: 9),   // 外
  Rectangle(top: 5, right: 15, bottom: 15, left: 5),   // 左上
  Rectangle(top: 5, right: 25, bottom: 15, left: 15),  // 右上
  Rectangle(top: 15, right: 25, bottom: 25, left: 15), // 右下
  Rectangle(top: 15, right: 15, bottom: 25, left: 5),  // 左下
  // ! overlapped
  Rectangle(top: 0, right: 10, bottom: 10, left: 0),   // 左上
  Rectangle(top: 0, right: 20, bottom: 10, left: 10),  // 上
  Rectangle(top: 0, right: 30, bottom: 10, left: 20),  // 右上
  Rectangle(top: 10, right: 30, bottom: 20, left: 20), // 右
  Rectangle(top: 20, right: 30, bottom: 30, left: 20), // 右下
  Rectangle(top: 20, right: 20, bottom: 30, left: 10), // 下
  Rectangle(top: 20, right: 10, bottom: 30, left: 0), // 左下
  Rectangle(top: 10, right: 10, bottom: 20, left: 0), // 左
].each {|r| r1.is_overlapped(r).p; }

関係ないコード(to_s)が入ってて微妙。。