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.

main.c 1.9KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394
  1. #include <math.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <time.h>
  5. #include <stdbool.h>
  6. #include "benchmark-data.h"
  7. /* Fonctions */
  8. double distance(const double (*u)[42], const double (*v)[42]);
  9. bool trouver_solution_initiale(void);
  10. void print_solution(int (*s)[230], const char *name);
  11. int solution[230] = {0};
  12. int n_clusters = 5;
  13. int main(int argc, char *argv[])
  14. {
  15. if (argc == 2) {
  16. int k = atoi(argv[1]);
  17. if (k > 0)
  18. n_clusters = k;
  19. }
  20. printf("Using %d clusters\n", n_clusters);
  21. srand(time(NULL));
  22. /* Solution initiale */
  23. while (!trouver_solution_initiale())
  24. ; /* do it again */
  25. print_solution(&solution, "initiale");
  26. exit(EXIT_SUCCESS);
  27. }
  28. double distance(const double (*u)[42], const double (*v)[42])
  29. {
  30. size_t n = sizeof(*v) / sizeof((*v)[0]);
  31. size_t i = 0;
  32. double sum = 0.0;
  33. printf("distance(): n = %zu\n", n);
  34. /* d(u, v) = sqrt( (u1 - v1)^2 + (u2 - v2)^2 + ... + (un - vn)^2 ) */
  35. for (; i < n; i++)
  36. sum += pow((*u)[i] - (*v)[i], 2);
  37. return sqrt(sum);
  38. }
  39. bool trouver_solution_initiale(void)
  40. {
  41. /* This function returns true if the solution that it found is "valid",
  42. * i.e., it has at least one element in each cluster. */
  43. bool *cluster_empty = calloc(n_clusters, sizeof *cluster_empty);
  44. bool ret = false;
  45. size_t i = 0;
  46. for (i = 0; i < (size_t) n_clusters; i++)
  47. cluster_empty[i] = true;
  48. for (i = 0; i < sizeof(solution) / sizeof(solution[0]); i++)
  49. cluster_empty[solution[i] = rand() % n_clusters] = false;
  50. for (i = 0; !ret && i < (size_t) n_clusters; ++i)
  51. ret = (ret || cluster_empty[i]);
  52. return !ret;
  53. }
  54. void print_solution(int (*s)[230], const char *name)
  55. {
  56. size_t i = 0, n = sizeof(*s) / sizeof((*s)[0]);
  57. printf("Solution%s%s:\n[", name ? " " : "", name ? name : "");
  58. while (i < n) {
  59. const char *end;
  60. if (i + 1 == n)
  61. end = "]\n";
  62. else if (i && i % 20 == 0)
  63. end = ",\n";
  64. else
  65. end = ", ";
  66. printf("%d%s", (*s)[i++], end);
  67. }
  68. }