-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathpolly.c
106 lines (75 loc) · 2.52 KB
/
polly.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
/* polly.c
Rank the desirability of suitors -- sorting example.
by: Steven Skiena
begun: February 5, 2002
*/
/*
Copyright 2003 by Steven S. Skiena; all rights reserved.
Permission is granted for use in non-commerical applications
provided this copyright notice remains intact and unchanged.
This program appears in my book:
"Programming Challenges: The Programming Contest Training Manual"
by Steven Skiena and Miguel Revilla, Springer-Verlag, New York 2003.
See our website www.programming-challenges.com for additional information.
This book can be ordered from Amazon.com at
http://www.amazon.com/exec/obidos/ASIN/0387001638/thealgorithmrepo/
*/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define NAMELENGTH 30 /* maximum length of name */
#define NSUITORS 100 /* maximum number of suitors */
#define BESTHEIGHT 180 /* best height in centimeters */
#define BESTWEIGHT 75 /* best weight in kilograms */
typedef struct {
char first[NAMELENGTH]; /* suitor's first name */
char last[NAMELENGTH]; /* suitor's last name */
int height; /* suitor's height */
int weight; /* suitor's weight */
} suitor;
suitor suitors[NSUITORS]; /* database of suitors */
int nsuitors; /* number of suitors */
void read_suitors(void) {
char first[NAMELENGTH], last[NAMELENGTH];
int height, weight;
nsuitors = 0;
while (scanf("%s %s %d %d\n",suitors[nsuitors].first,
suitors[nsuitors].last, &height, &weight) != EOF) {
suitors[nsuitors].height = abs(height - BESTHEIGHT);
if (weight > BESTWEIGHT) {
suitors[nsuitors].weight = weight - BESTWEIGHT;
} else {
suitors[nsuitors].weight = - weight;
}
nsuitors ++;
}
}
int main(void) {
int i; /* counter */
int suitor_compare();
read_suitors();
qsort(suitors, nsuitors, sizeof(suitor), suitor_compare);
for (i = 0; i < nsuitors; i++) {
printf("%s, %s\n",suitors[i].last, suitors[i].first);
}
return 0;
}
int suitor_compare(suitor *a, suitor *b) {
int result; /* result of comparsion */
if (a->height < b->height) {
return(-1);
}
if (a->height > b->height) {
return(1);
}
if (a->weight < b->weight) {
return(-1);
}
if (a->weight > b->weight) {
return(1);
}
if ((result = strcmp(a->last, b->last)) != 0) {
return result;
}
return(strcmp(a->first, b->first));
}