informaticage

Longest distance between circumferences

Jun 26th, 2021 (edited)
428
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.67 KB | None | 0 0
  1. #include <math.h>
  2. #include <stdio.h>
  3. #define N 5
  4.  
  5. typedef struct {
  6.   double x;
  7.   double y;
  8.   double radius;
  9. } Circumference;
  10.  
  11. double compute_distance(Circumference c1, Circumference c2);
  12. double compute_longest_distance(Circumference circumferences[], size_t length);
  13.  
  14. int main(void) {
  15.   Circumference circumferences[N];
  16.  
  17.   printf("Insert %d circumferences [x y radius]: ", N);
  18.   for (size_t i = 0; i < N; i++) {
  19.     scanf("%lf %lf %lf", &circumferences[i].x, &circumferences[i].y,
  20.           &circumferences[i].radius);
  21.   }
  22.  
  23.   printf("Longest distance: %.4lf", compute_longest_distance(circumferences, N));
  24.   return 0;
  25. }
  26.  
  27. double compute_distance(Circumference c1, Circumference c2) {
  28.   // (x2 - x1) ^ 2 + (y2 - y1) ^ 2
  29.   double sq_distance =
  30.       (c1.x - c2.x) * (c1.x - c2.x) + (c2.y - c1.y) * (c2.y - c1.y);
  31.  
  32.   double abs_distance = sq_distance >= 0 ? sq_distance : -sq_distance;
  33.   // sqrt( (x2 - x1) ^ 2 + (y2 - y1) ^ 2 )
  34.  
  35.   // Substract (c1.radius + c2.radius) for distance between borders
  36.   return sqrt(abs_distance);
  37. }
  38.  
  39. double compute_longest_distance(Circumference circumferences[], size_t length) {
  40.   if (length <= 0) return -1.0;
  41.   if (length == 1) return 0.0;
  42.  
  43.   double longest_distance = 0.0;
  44.  
  45.   for (size_t i = 0; i < length; i++) {
  46.     for (size_t j = i + 1; j < length; j++) {
  47.  
  48.       // Computing distance between circumferences[i] and circumferences[j]
  49.       double current_distance =
  50.           compute_distance(circumferences[i], circumferences[j]);
  51.  
  52.       // Longer then the previous best
  53.       if (current_distance > longest_distance) {
  54.         longest_distance = current_distance;
  55.       }
  56.     }
  57.   }
  58.  
  59.   return longest_distance;
  60. }
Add Comment
Please, Sign In to add comment