[英]Using arrays instead of vectors in C
Program should find smallest enclosing circle of two points.程序应该找到两点的最小外接圆。
EXAMPLE: (1,1) (2,2)示例:(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.这两个点的最小圆将是中心为 (1.5, 1,5) 且半径为 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?
如果不使用向量并使用 C arrays 怎么写呢?
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 c 中的普通数组没有像 size() 这样的方法,在你的代码中你需要用指针传递 size 参数而不是 vector::size() 和 -> 它可以很好地工作
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测试于: https://godbolt.org/z/xWTqfqxsn
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.