|
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127 |
- /* Quick voting software.
- * Usage:
- * vote <file1> <file2> ...
- * File format:
- * <key1> <value1>
- * <key1> <value1>
- */
-
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
-
- #define MAXLEN 20
- #define MAXITEMS 2000
-
- static char *items[MAXITEMS];
- static int nitems;
-
- static int *matrix;
-
- static int lookup(char const *str)
- {
- int i;
-
- for(i = 0; i < nitems; i++)
- if(!strcmp(str, items[i]))
- return i;
-
- return -1;
- }
-
- static int record(char const *str)
- {
- int n = lookup(str);
-
- if(n >= 0)
- return n;
-
- items[nitems] = strdup(str);
- return nitems++;
- }
-
- static void recordfile(char const *file)
- {
- char buf[MAXLEN];
- FILE *f;
- float val;
-
- f = fopen(file, "r");
- if(!f)
- return;
- while(!feof(f))
- {
- fscanf(f, "%s %g", buf, &val);
- record(buf);
- }
- fclose(f);
- }
-
- static void readfile(char const *file)
- {
- float values[MAXITEMS];
- char buf[MAXLEN];
- FILE *f;
- float val;
- int n, i, j;
-
- for(i = 0; i < nitems; i++)
- values[i] = 9999.;
-
- f = fopen(file, "r");
- if(!f)
- return;
- while(!feof(f))
- {
- fscanf(f, "%s %g", buf, &val);
- n = lookup(buf);
- values[n] = val;
- }
- fclose(f);
-
- for(j = 0; j < nitems; j++)
- for(i = j + 1; i < nitems; i++)
- if(values[i] < values[j])
- matrix[j * nitems + i]++;
- else if(values[i] > values[j])
- matrix[i * nitems + j]++;
- }
-
- static void solvematrix(void)
- {
- int wins[MAXITEMS];
- int i, j;
-
- memset(wins, 0, MAXITEMS * sizeof(int));
-
- for(j = 0; j < nitems; j++)
- for(i = j + 1; i < nitems; i++)
- {
- if(matrix[j * nitems + i] > matrix[i * nitems + j])
- wins[i]++;
- else
- wins[j]++;
- }
-
- for(i = 0; i < nitems; i++)
- printf("%s (%i): %i wins\n", items[i], i, wins[i]);
- }
-
- int main(int argc, char *argv[])
- {
- int i;
-
- for(i = 1; i < argc; i++)
- recordfile(argv[i]);
-
- matrix = malloc(nitems * nitems * sizeof(int));
- memset(matrix, 0, nitems * nitems * sizeof(int));
-
- for(i = 1; i < argc; i++)
- readfile(argv[i]);
-
- solvematrix();
-
- return 0;
- }
-
|