/* one input: number of rectangles output: each line- id (starting from 0) width height area The width is no larger than the height for each rectangle. Each rectangle has a distinct set of width and height. The rectangles are sorted by areas. */ /* ECE 264 Yung-Hsiang Lu, Purdue Spring 2009 */ #include #include #include typedef struct { int width; int height; } Rectangle; int checkRect(Rectangle * rect, int numRect, int width, int height) { /* Is there an existing rectangle of the same width and height? */ int rcnt = 0; int differentRect = 1; while ((differentRect == 1) && (rcnt < numRect)) { if ((rect[rcnt].width == width) && (rect[rcnt].height == height)) { differentRect = 0; } /* check rotation */ if ((rect[rcnt].width == height) && (rect[rcnt].height == width)) { differentRect = 0; } rcnt ++; } return differentRect; } void swapRect(Rectangle * rect1, Rectangle * rect2) { int w = rect1 -> width; int h = rect1 -> height; rect1 -> width = rect2 -> width; rect1 -> height = rect2 -> height; rect2 -> width = w; rect2 -> height = h; } void sortRect(Rectangle * rect, int numRect) { /* sort by areas */ int rcnt1; int rcnt2; for (rcnt1 = 0; rcnt1 < numRect - 1; rcnt1 ++) { for (rcnt2 = rcnt1; rcnt2 < numRect; rcnt2 ++) { int area1 = rect[rcnt1].width * rect[rcnt1].height; int area2 = rect[rcnt2].width * rect[rcnt2].height; if (area1 > area2) { swapRect(& rect[rcnt1], & rect[rcnt2]); } } } } int main(int argc, char * argv[]) { int numRect; Rectangle * rect; int rcnt; if (argc < 2) { printf("need a number\n"); return -1; } numRect = strtol(argv[1], NULL, 10); if (numRect <= 10) { printf("must be a positive number larger than 10\n"); return -1; } rect = malloc(numRect * sizeof(Rectangle)); for (rcnt = 0; rcnt < numRect; rcnt ++) { rect[rcnt].width = 0; rect[rcnt].height = 0; } srand (time(NULL)); for (rcnt = 0; rcnt < numRect; rcnt ++) { int differentRect = 1; int width; int height; do { width = rand() % (3 * numRect) + 1; /* must not be zero */ height = rand() % (3 * numRect) + 1; differentRect = checkRect(rect, rcnt - 1, width, height); } while (differentRect == 0); rect[rcnt].width = width; rect[rcnt].height = height; } sortRect(rect, numRect); for (rcnt = 0; rcnt < numRect; rcnt ++) { printf("%d ", rcnt); if (rect[rcnt].width < rect[rcnt].height) { printf("%d %d ", rect[rcnt].width, rect[rcnt].height); } else { printf("%d %d ", rect[rcnt].height, rect[rcnt].width); } printf("%d\n", rect[rcnt].height * rect[rcnt].width); } free (rect); return 0; }