diff options
| author | Mattias Andrée <maandree@kth.se> | 2016-06-19 02:50:31 +0200 |
|---|---|---|
| committer | Mattias Andrée <maandree@kth.se> | 2016-06-19 02:50:31 +0200 |
| commit | a049db580776ed41bb4583bfb331d97c5a80900a (patch) | |
| tree | 07c663214541da3ec94f0913b2ab78334bf7b6f6 /examples/04-median.c | |
| parent | doc: vulnerabilities concerning cryptographic applications (diff) | |
| download | libzahl-a049db580776ed41bb4583bfb331d97c5a80900a.tar.gz libzahl-a049db580776ed41bb4583bfb331d97c5a80900a.tar.bz2 libzahl-a049db580776ed41bb4583bfb331d97c5a80900a.tar.xz | |
Add examples: sum, prod, avg, median
Signed-off-by: Mattias Andrée <maandree@kth.se>
Diffstat (limited to '')
| -rw-r--r-- | examples/04-median.c | 63 |
1 files changed, 63 insertions, 0 deletions
diff --git a/examples/04-median.c b/examples/04-median.c new file mode 100644 index 0000000..7acff70 --- /dev/null +++ b/examples/04-median.c @@ -0,0 +1,63 @@ +/* Calculates the median of $@ */ + +#include <stdio.h> +#include <stdlib.h> + +#include <zahl.h> + +int +main(int argc, char *argv[]) +{ + struct zahl *values; + z_t med, medmod; + jmp_buf env; + char *buf, *argv0; + int i, j; + + argv0 = *argv++, argc--; + + if (!argc) { + fprintf(stderr, + "%s: cannot calculate median of the empty bag\n", + argv0); + return 1; + } + + values = calloc(argc, sizeof(*values)); + if (!values) + return perror(argv0), 1; + + if (setjmp(env)) + return zperror(argv0), 1; + + zsetup(env); + zinit(med); + zinit(medmod); + + /* Since `values` where allocated with + * `calloc` it is already cleared and + * `zinit` is not necessary. */ + + for (i = 0; i < argc; i++) + zsets(&values[i], argv[i]); + + qsort(values, argc, sizeof(*values), + (int (*)(const void *, const void *))zcmp); + i = argc / 2; + j = i - !(argc & 1); + zadd(med, &values[i], &values[j]); + zsetu(medmod, 2); + zdivmod(med, medmod, med, medmod); + + printf("%s%s\n", buf = zstr(med, NULL, 0), + (const char *[]){"", ".5"}[zodd(medmod)]); + free(buf); + + zfree(medmod); + zfree(med); + for (i = 0; i < argc; i++) + zfree(&values[i]); + free(values); + zunsetup(); + return 0; +} |
