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.
 
 
 
 

125 line
2.1 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. f = fopen(file, "r");
  55. if(!f)
  56. return;
  57. while(!feof(f))
  58. {
  59. fscanf(f, "%s %g", buf, &val);
  60. n = lookup(buf);
  61. values[n] = val;
  62. }
  63. fclose(f);
  64. for(j = 0; j < nitems; j++)
  65. for(i = j + 1; i < nitems; i++)
  66. if(values[i] < values[j])
  67. matrix[j * nitems + i]++;
  68. else if(values[i] > values[j])
  69. matrix[i * nitems + j]++;
  70. }
  71. static void solvematrix(void)
  72. {
  73. int wins[MAXITEMS];
  74. int i, j;
  75. memset(wins, 0, MAXITEMS * sizeof(int));
  76. for(j = 0; j < nitems; j++)
  77. for(i = j + 1; i < nitems; i++)
  78. {
  79. if(matrix[j * nitems + i] > matrix[i * nitems + j])
  80. wins[i]++;
  81. else
  82. wins[j]++;
  83. }
  84. for(i = 0; i < nitems; i++)
  85. printf("%s (%i): %i wins\n", items[i], i, wins[i]);
  86. }
  87. int main(int argc, char *argv[])
  88. {
  89. int i;
  90. for(i = 1; i < argc; i++)
  91. recordfile(argv[i]);
  92. matrix = malloc(nitems * nitems * sizeof(int));
  93. memset(matrix, 0, nitems * nitems * sizeof(int));
  94. for(i = 1; i < argc; i++)
  95. readfile(argv[i]);
  96. solvematrix();
  97. return 0;
  98. }