Skip to content

Instantly share code, notes, and snippets.

@giuniu
Forked from skRyo/View.java
Created August 8, 2012 01:23
Show Gist options
  • Save giuniu/3291199 to your computer and use it in GitHub Desktop.
Save giuniu/3291199 to your computer and use it in GitHub Desktop.
教えてエライ人3
package com.example;
public class Control {
public static void main(String[] args) {
Model.Rectangle r1 = new Model.Rectangle(1, 2, 3, 4);
Model.Rectangle r2 = new Model.Rectangle(2, 3, 5, 5);
new Control().execute(r1, r2);
}
public void execute(Model.Rectangle r1, Model.Rectangle r2) {
Model model = new Model();
Model.Rectangle overlapped = model.calcOverlapped(r1, r2);
View view = new View(r1, r2, overlapped);
view.showResult();
}
}
class Model {
//重なった四角形の計算
public Rectangle calcOverlapped(Rectangle r1, Rectangle r2) {
Rectangle result;
if (isOverlap(r1, r2)) {
//重なった四角形の頂点を求める
int x = Math.max(r1.x, r2.x);
int y = Math.max(r1.y, r2.y);
//重なった四角形の辺と高さを求める
int work_w = Math.min((r1.x + r1.width), (r2.x + r2.width));
int work_h = Math.min((r1.y + r1.height), (r2.y + r2.height));
int w = work_w - x;
int h = work_h - y;
result = new Rectangle(x, y, w, h);
} else {
result = null;
}
return result;
}
public boolean isOverlap(Rectangle r1, Rectangle r2) {
return (r1.x + r1.width > r2.x && r2.x + r2.width > r1.x)
&& (r1.y + r1.height > r2.y && r2.y + r2.height > r2.y);
}
public static class Rectangle {
final int x;
final int y;
final int width;
final int height;
final int area;
public Rectangle(int x, int y, int width, int height) {
this.x = x;
this.y = y;
this.width = width;
this.height = height;
area = width * height;
}
}
}
class View {
private final Model.Rectangle r1;
private final Model.Rectangle r2;
private final Model.Rectangle overlapped;
public View(Model.Rectangle r1, Model.Rectangle r2, Model.Rectangle overlapped) {
this.r1 = r1;
this.r2 = r2;
this.overlapped = overlapped;
}
public void showResult() {
//面積
System.out.println(r1.area);
System.out.println(r2.area);
if (overlapped == null) {
System.out.println("重なった部分はありません。");
} else {
//重なった四角形の頂点
System.out.println("x = " + overlapped.x);
System.out.println("y = " + overlapped.y);
//重なった四角形の面積
System.out.println(overlapped.area);
}
}
}
@giuniu
Copy link
Author

giuniu commented Aug 8, 2012

さらにさらに蛇足ですが、もしRectangle#calcArea()が必ず呼ばれるような性質のものであれば、予め計算しておくことで呼び出されるたびに再計算するコストを抑えることができます。(代わりにキャッシュ分のメモリを喰うわけですが)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment