Problem Statement
I have given N number of rectangles(input from user) whose length and width are taken as an input from user also.
I have to select maximum number of rectangles with a condition that length of first rectangle > length of second rectangle and width of first rectangle > width of second rectangle.
My Procedure
What I am doing is I am sorting each rectangle with respect to length and width, and then considering only those rectangle whose length and width are in increasing order, but my sorting is not working properly.
#include<stdio.h>
#include<stdlib.h>
#define MAX 100
typedef struct
{
int length;
int width;
}Rectangles;
int compare(const void *first,const void *second)
{
const Rectangles *rect1 = first;
const Rectangles *rect2 = second;
if(rect1->length > rect2->length )
{
if(rect1->width > rect2->width)
return 1;
else if(rect1->width < rect2->width)
return -1;
else
return -1;
}
else if(rect1->length < rect2->length )
{
if(rect1->width < rect2->width)
return -1;
else if(rect1->width > rect2->width)
return -1;
else
return -1;
}
else
{
if(rect1->width < rect2->width)
return -1;
else if(rect1->width > rect2->width)
return -1;
else
return 0;
}
}
int main()
{
int i,nRectangleCount;
Rectangles stRectangle[MAX];
printf("Enter total number of rectangles\n");
scanf("%d",&nRectangleCount);
printf("Enter %d length and width of rectanle\n",nRectangleCount);
for(i=0;i<nRectangleCount;++i)
{
scanf("%d %d",&stRectangle[i].length,&stRectangle[i].width);
}
printf("Before Sorting\n");
for(i=0;i<nRectangleCount;++i)
{
printf("%d %d\n", stRectangle[i].length,stRectangle[i].width);
}
qsort(stRectangle,nRectangleCount,sizeof(Rectangles),compare);
printf("\n\nAfter Sorting\n");
for(i=0;i<nRectangleCount;++i)
{
printf("%d %d\n", stRectangle[i].length,stRectangle[i].width);
}
return 0;
}
I don't think, it is good idea to solve this question with sorting, I tried to calculate area and then sort it with respect to area, then also it is not working.
Is there any other algorithm to solve this problem.?
Here is the test case:
7
10 12
4 5
15 8
3 18
16 25
1 2
5 10