Find minimum radius such that atleast k point lie inside the circle in C++



Suppose we have some points, and one integer k. We have to find minimum radius of a circle whose center is at (0, 0) to cover k points. So if the points are like (1, 1), (-1, -1), (1, -1), and k = 3, then radius will be 2.

Here we will find the Euclidean distance between each point and (0, 0), then sort the distances and return the kth element after sorting.

Example

 Live Demo

#include<iostream>
#include<algorithm>
using namespace std;
struct point{
   int x, y;
};
int minRadius(int k, point points[], int n) {
   int dist[n];
   for (int i = 0; i < n; i++)
   dist[i] = points[i].x * points[i].x + points[i].y * points[i].y;
   // Sorting the distance
   sort(dist, dist + n);
   return dist[k - 1];
}
int main() {
   int k = 3;
   point points[] = {{1, 1}, {-1, -1}, {1, -1}};
   int n = sizeof(points)/sizeof(points[0]);
   cout << "Minimum radius: " << minRadius(k, points, n) << endl;
}

Output

Minimum radius: 2

Advertisements