Home > front end >  Using arrays instead of vectors in C
Using arrays instead of vectors in C

Time:03-10

Program should find smallest enclosing circle of two points.

EXAMPLE: (1,1) (2,2)

The smallest circle for these two points would be the circle with center(1.5, 1,5) and radius 0.71. This is just a representation of that on a graph: Two points inside a circle

Here's the problem solution:

#include <iostream>
#include <math.h>
#include <vector>
using namespace std;
const double INF = 1e18;
struct Point {
    double X, Y;
};
struct Circle {
    Point C;
    double R;
};
double dist(const Point& a, const Point& b)
{ return sqrt(pow(a.X - b.X, 2)   pow(a.Y - b.Y, 2)); }

int is_inside(const Circle& c, const Point& p)
{ return dist(c.C, p) <= c.R; }

Circle circle_from(const Point& A, const Point& B)
{
    Point C = { (A.X   B.X) / 2.0, (A.Y   B.Y) / 2.0 };
    return { C, dist(A, B) / 2.0 };
}

int is_valid_circle(const Circle& c, const vector<Point>& P)
{
    for (const Point& p : P)
        if (!is_inside(c, p)) return 0;
    return 1;
}

Circle minimum_enclosing_circle(const vector<Point>& P)
{
    int n = (int)P.size();
    if (n == 0)
        return { { 0, 0 }, 0 };
    if (n == 1)
        return { P[0], 0 };
    Circle mec = { { 0, 0 }, INF };
    for (int i = 0; i < n; i  ) {
        for (int j = i   1; j < n; j  ) {
            Circle tmp = circle_from(P[i], P[j]);
            if (tmp.R < mec.R && is_valid_circle(tmp, P))
                mec = tmp;
        }
    }
    return mec;
}
int main() {
  Circle mec = minimum_enclosing_circle({
      {1, 1},
      {2, 2},
  });
  printf("(%.2f,%.2f) %.2f", mec.C.X, mec.C.Y, mec.R);
  return 0;
}
int main() {
  Circle mec = minimum_enclosing_circle({
      {1, 1},
      {2, 2},
  });
  printf("(%.2f,%.2f) %.2f", mec.C.X, mec.C.Y, mec.R);
  return 0;
}

Problem with this code is using vectors for calculations. How could this be written without using vectors and with using C arrays?

CodePudding user response:

normal array in c don't have some method like size() , in your code you need to pass size parameter with pointer instead of vector::size() and -> it can work well

int is_valid_circle(const Circle c, const Point* P, size_t size)
{
    for(int i = 0; i < size ; i  )
    {
        if (!is_inside(c, P[i])) return 0;
    }

    return 1;
}

Circle minimum_enclosing_circle(const Point* P, size_t size)
{
    int n = size;
    if (n == 0)
        return { { 0, 0 }, 0 };
    if (n == 1)
        return { P[0], 0 };
    Circle mec = { { 0, 0 }, INF };
    for (int i = 0; i < n; i  ) {
        for (int j = i   1; j < n; j  ) {
            Circle tmp = circle_from(P[i], P[j]);
            if (tmp.R < mec.R && is_valid_circle(tmp, P, size))
                mec = tmp;
        }
    }
    return mec;
}

tested at : https://godbolt.org/z/xWTqfqxsn

  • Related