求两个矩形相交的公共面积,这是今天的面试题,实话讲,太紧张了,回答的并不好,而且自己的思路只能在二维的情况下解出来,三维的情况将会变得非常麻烦。面试官提示的解法不仅适用于二维,多维也适用。自己差的是编程思想,在一个心理素质太差,太紧张了,思想都给出来了,自己都没能实现,我也是服了我自己。
#include <iostream>
#include <algorithm>
using namespace std;
struct node {
double x;
double y;
};
struct rectangle {
struct node leftdown;
struct node rightup;
};
/*
自己的方法,容易出错,而且到多维的情况不能使用。
double cal(const struct rectangle& rec1, const struct rectangle& rec2) {
double ans = 0;
if (!(rec1.leftdown.x >= rec2.rightup.x || rec1.rightup.x <= rec2.leftdown.x || rec1.leftdown.y >= rec2.rightup.x ||
rec1.rightup.y <= rec2.leftdown.y)) {
ans = abs(max(rec1.leftdown.x, rec2.leftdown.x) - min(rec1.rightup.x, rec2.rightup.x)) * abs(max(rec1.leftdown.y, rec2.leftdown.y) - min(rec1.rightup.y, rec2.rightup.y));
}
return ans;
}
*/
/*
面试官老师的思路,把问题简化成一维的情况解决,这样不止适用于二维的情况,多维的情况同样适用,
当时面试官让写cha函数都没有能写出来,唉,真是个垃圾。
*/
double cha(const double& rec1start, const double& rec1end, const double& rec2start, const double& rec2end) {
double ans = 0;
if (!(rec1start >= rec2end || rec1end <= rec2start)) {
ans = min(rec1end, rec2end) - max(rec1start, rec2start);
}
return ans;
}
double cal1(const struct rectangle& rec1, const struct rectangle& rec2) {
double tempx = cha(rec1.leftdown.x, rec1.rightup.x, rec2.leftdown.x, rec2.rightup.x);
double tempy = cha(rec1.leftdown.y, rec1.rightup.y, rec2.leftdown.y, rec2.rightup.y);
return tempx * tempy;
}
int main() {
rectangle rec1, rec2;
rec1.leftdown.x = -1;
rec1.leftdown.y = -1;
rec1.rightup.x = 3;
rec1.rightup.y = 3;
rec2.leftdown.x = 0;
rec2.leftdown.y = 0;
rec2.rightup.x = 5;
rec2.rightup.y = 5;
cout << cal1(rec1, rec2) << endl;
return 0;
}