Skip to content

Instantly share code, notes, and snippets.

@RIscRIpt
Created October 13, 2014 19:41
Show Gist options
  • Save RIscRIpt/155a0d2ffb15eea39d96 to your computer and use it in GitHub Desktop.
Save RIscRIpt/155a0d2ffb15eea39d96 to your computer and use it in GitHub Desktop.
Find common area of two rectangles
#include <stdio.h>
#include <stdlib.h>
#define inline __inline
#define ARRAY_SIZE(a) (sizeof(a) / sizeof(a[0]))
typedef struct {
double x, y;
} point_t;
int cmp_points_x(const point_t *p1, const point_t *p2) {
if(p1->x > p2->x)
return 1;
else if(p1->x < p2->x)
return -1;
else {
if(p1->y > p2->y)
return 1;
else if(p1->y < p2->y)
return -1;
else
return 0;
}
}
int cmp_points_y(const point_t *p1, const point_t *p2) {
if(p1->y > p2->y)
return 1;
else if(p1->y < p2->y)
return -1;
else {
if(p1->x > p2->x)
return 1;
else if(p1->x < p2->x)
return -1;
else
return 0;
}
}
inline double rect_area(const point_t *points) {
return (points[0].x - points[3].x) * (points[0].y - points[3].y);
}
inline double d_min(double a, double b) {
return a > b ? a : b;
}
int main(void) {
int i;
double area, min_area;
point_t points[8], *pp;
for(i = 0; i < 2; i++) {
pp = &points[i * 4];
//Get two points of first rectangle
printf("\nRectangle: %i\n", i + 1);
printf("\t%48s: ", "Base point coord (X Y)");
scanf("%lf %lf", &pp[0].x, &pp[0].y);
printf("\t%48s: ", "Opposite (diagonal) point coordinate (X Y)");
scanf("%lf %lf", &pp[3].x, &pp[3].y);
pp[1].x = pp[3].x;
pp[1].y = pp[0].y;
pp[2].x = pp[0].x;
pp[2].y = pp[3].y;
}
min_area = d_min(rect_area(&points[0]), rect_area(&points[4]));
qsort(points, ARRAY_SIZE(points), sizeof(points[0]), cmp_points_x);
area = points[5].x - points[3].x;
qsort(points, ARRAY_SIZE(points), sizeof(points[0]), cmp_points_y);
area *= points[5].y - points[3].y;
//TODO: better way to check if rectangles don't have common area
if(area <= min_area)
printf("Common area: %lf square units\n", area);
else
printf("No common area!\n");
getch();
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment