|
- /* 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;
- }
|