-
Notifications
You must be signed in to change notification settings - Fork 43
/
3.c
108 lines (91 loc) · 2.48 KB
/
3.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
107
108
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define HCAP (4096)
struct result {
char city[100];
int count;
double sum, min, max;
};
static const char *parse_double(double *dest, const char *s) {
// parse sign
double mod;
if (*s == '-') {
mod = -1.0;
s++;
} else {
mod = 1.0;
}
if (s[1] == '.') {
*dest = (((double)s[0] + (double)s[2] / 10.0) - 1.1 * '0') * mod;
return s + 4;
}
*dest =
((double)((s[0]) * 10 + s[1]) + (double)s[3] / 10.0 - 11.1 * '0') * mod;
return s + 5;
}
// hash returns a simple (but fast) hash for the first n bytes of data
static unsigned int hash(const unsigned char *data, int n) {
unsigned int hash = 0;
for (int i = 0; i < n; i++) {
hash = (hash * 31) + data[i];
}
return hash;
}
static int cmp(const void *ptr_a, const void *ptr_b) {
return strcmp(((struct result *)ptr_a)->city, ((struct result *)ptr_b)->city);
}
int main(int argc, const char **argv) {
const char *file = "measurements.txt";
if (argc > 1) {
file = argv[1];
}
FILE *fh = fopen(file, "r");
if (!fh) {
perror("error opening file");
exit(EXIT_FAILURE);
}
struct result results[450];
int nresults = 0;
char buf[1 << 10];
int map[HCAP];
memset(map, -1, HCAP * sizeof(int));
while (fgets(buf, 1 << 10, fh)) {
char *pos = strchr(buf, ';');
*pos = 0x0;
double measurement;
parse_double(&measurement, pos + 1);
// find index of group by key through hash with linear probing
int h = hash((unsigned char *)buf, pos - buf) & (HCAP - 1);
while (map[h] != -1 && strcmp(results[map[h]].city, buf) != 0) {
h = (h + 1) & (HCAP - 1);
}
int c = map[h];
if (c < 0) {
strcpy(results[nresults].city, buf);
results[nresults].sum = measurement;
results[nresults].max = measurement;
results[nresults].min = measurement;
results[nresults].count = 1;
map[h] = nresults;
nresults++;
} else {
results[c].sum += measurement;
results[c].count += 1;
if (results[c].min > measurement) {
results[c].min = measurement;
}
if (results[c].max < measurement) {
results[c].max = measurement;
}
}
}
qsort(results, (size_t)nresults, sizeof(*results), cmp);
for (int i = 0; i < nresults; i++) {
printf("%s=%.1f/%.1f/%.1f%s", results[i].city, results[i].min,
results[i].sum / results[i].count, results[i].max,
i < nresults ? ", " : "");
}
puts("\n");
fclose(fh);
}