Advertisement
cd62131

find closest points

Jan 14th, 2019
541
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.08 KB | None | 0 0
  1. #include <float.h>
  2. #include <stdio.h>
  3. #include <stdlib.h>
  4. #include <tgmath.h>
  5. static void data_read(int *n, double complex **p) {
  6.   FILE *in = fopen("data.txt", "r");
  7.   if (fscanf(in, "%d", n) != 1) {
  8.     exit(1);
  9.   }
  10.   *p = calloc(sizeof(**p), *n);
  11.   for (int i = 0; i < *n; ++i) {
  12.     double x, y;
  13.     if (fscanf(in, "%lf%lf", &x, &y) != 2) {
  14.       exit(1);
  15.     }
  16.     (*p)[i] = CMPLX(x, y);
  17.   }
  18.   fclose(in);
  19. }
  20. static void find_closest_points(int n, double complex *p, int *index,
  21.                                 double *min) {
  22.   *min = DBL_MAX;
  23.   for (int i = 0; i < n; ++i) {
  24.     for (int j = i + 1; j < n; ++j) {
  25.       double dist = fabs(p[i] - p[j]);
  26.       if (dist < *min) {
  27.         *min = dist;
  28.         index[0] = i;
  29.         index[1] = j;
  30.       }
  31.     }
  32.   }
  33. }
  34. static void report(int *index, double min) {
  35.   printf("%d %d %f\n", index[0], index[1], min);
  36. }
  37. int main(void) {
  38.   int n;
  39.   double complex *p;
  40.   data_read(&n, &p);
  41.   {
  42.     int index[2];
  43.     double min;
  44.     find_closest_points(n, p, index, &min);
  45.     report(index, min);
  46.   }
  47.   free(p);
  48. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement