diff --git a/2008-displacement/.gitignore b/2008-displacement/.gitignore index 2cdf196..45a28dc 100644 --- a/2008-displacement/.gitignore +++ b/2008-displacement/.gitignore @@ -4,3 +4,4 @@ main *.log *.pdf xy2d +vote diff --git a/2008-displacement/Makefile b/2008-displacement/Makefile index a046819..0624388 100644 --- a/2008-displacement/Makefile +++ b/2008-displacement/Makefile @@ -1,11 +1,14 @@ -all: main xy2d +all: main xy2d vote xy2d: xy2d.c $(CC) -W -Wall $^ -o $@ +vote: vote.c + $(CC) -W -Wall $^ -o $@ + main: main.c $(CC) -Wall -O3 -funroll-loops -ffast-math -W -Wall $^ -o $@ $$(pkg-config --cflags --libs sdl) -lSDL_image -lm clean: - rm -f xy2d main + rm -f xy2d vote main diff --git a/2008-displacement/vote.c b/2008-displacement/vote.c new file mode 100644 index 0000000..2871275 --- /dev/null +++ b/2008-displacement/vote.c @@ -0,0 +1,124 @@ +/* Quick voting software. + * Usage: + * vote ... + * File format: + * + * + */ + +#include +#include +#include + +#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; + + 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; +} +