You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

128 lines
2.2 KiB

  1. /* Quick voting software.
  2. * Usage:
  3. * vote <file1> <file2> ...
  4. * File format:
  5. * <key1> <value1>
  6. * <key1> <value1>
  7. */
  8. #include <stdio.h>
  9. #include <string.h>
  10. #include <stdlib.h>
  11. #define MAXLEN 20
  12. #define MAXITEMS 2000
  13. static char *items[MAXITEMS];
  14. static int nitems;
  15. static int *matrix;
  16. static int lookup(char const *str)
  17. {
  18. int i;
  19. for(i = 0; i < nitems; i++)
  20. if(!strcmp(str, items[i]))
  21. return i;
  22. return -1;
  23. }
  24. static int record(char const *str)
  25. {
  26. int n = lookup(str);
  27. if(n >= 0)
  28. return n;
  29. items[nitems] = strdup(str);
  30. return nitems++;
  31. }
  32. static void recordfile(char const *file)
  33. {
  34. char buf[MAXLEN];
  35. FILE *f;
  36. float val;
  37. f = fopen(file, "r");
  38. if(!f)
  39. return;
  40. while(!feof(f))
  41. {
  42. fscanf(f, "%s %g", buf, &val);
  43. record(buf);
  44. }
  45. fclose(f);
  46. }
  47. static void readfile(char const *file)
  48. {
  49. float values[MAXITEMS];
  50. char buf[MAXLEN];
  51. FILE *f;
  52. float val;
  53. int n, i, j;
  54. for(i = 0; i < nitems; i++)
  55. values[i] = 9999.;
  56. f = fopen(file, "r");
  57. if(!f)
  58. return;
  59. while(!feof(f))
  60. {
  61. fscanf(f, "%s %g", buf, &val);
  62. n = lookup(buf);
  63. values[n] = val;
  64. }
  65. fclose(f);
  66. for(j = 0; j < nitems; j++)
  67. for(i = j + 1; i < nitems; i++)
  68. if(values[i] < values[j])
  69. matrix[j * nitems + i]++;
  70. else if(values[i] > values[j])
  71. matrix[i * nitems + j]++;
  72. }
  73. static void solvematrix(void)
  74. {
  75. int wins[MAXITEMS];
  76. int i, j;
  77. memset(wins, 0, MAXITEMS * sizeof(int));
  78. for(j = 0; j < nitems; j++)
  79. for(i = j + 1; i < nitems; i++)
  80. {
  81. if(matrix[j * nitems + i] > matrix[i * nitems + j])
  82. wins[i]++;
  83. else
  84. wins[j]++;
  85. }
  86. for(i = 0; i < nitems; i++)
  87. printf("%s (%i): %i wins\n", items[i], i, wins[i]);
  88. }
  89. int main(int argc, char *argv[])
  90. {
  91. int i;
  92. for(i = 1; i < argc; i++)
  93. recordfile(argv[i]);
  94. matrix = malloc(nitems * nitems * sizeof(int));
  95. memset(matrix, 0, nitems * nitems * sizeof(int));
  96. for(i = 1; i < argc; i++)
  97. readfile(argv[i]);
  98. solvematrix();
  99. return 0;
  100. }