2012年3月4日日曜日

重なりあう長方形の面積(解答)

前回の問題の解答の一つを示す(解答はもちろん一つではない)。
上図のように、辺同士の重なりをチェックすれば、重なりあう長さがわかる。
重なりあう長さがわかれば、あとは掛け算するだけだ。
重なりあいの場合分けは、6通りある。

Cで書いたサンプルコードは以下。
バグがあるかもしれないから、ちゃんと検証して使うように。




#include

int sharedRect(int xa, int ya, int wa, int ha, int xb, int yb, int wb, int hb);
int sharedLine(int s1, int l1, int s2, int l2);

int main (int argc, char * const argv[]) {
int xa, ya, wa, ha, xb, yb, wb, hb;
  xa = 0;  ya = 0;  wa = 100; ha = 200;
  xb = 10; yb = 15; wb = 80;  hb = 220;
  std::cout << sharedRect(xa, ya, wa, ha, xb, yb, wb, hb);
  return 0;
}

int sharedRect(int xa, int ya, int wa, int ha, int xb, int yb, int wb, int hb) {
  return sharedLine(xa, wa, xb, wb) * sharedLine(ya, ha, yb, hb);
};

int sharedLine(int s1, int l1, int s2, int l2) {
  int e1 = s1 + l1 - 1;
  int e2 = s2 + l2 - 1;

  if (s1 < s2) {
    if (e1 < s2) return 0;
    else if (e1 < e2) return e1 - s2 + 1;
    else return l2;
  } else if (s1 < e2) {
    if (e1 < e2) return l1;
    else return e2 - s1 + 1;
  } else return 0;

};


// 情けない。さっそく間違っていた。